﻿using AoYing_DeviceCollection.Model;
using MySqlX.XDevAPI.Common;
using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Windows.Media;
using System.Xml.Linq;
using static System.Windows.Forms.LinkLabel;
using System.IO.Ports;
using System.Configuration;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System.Text.RegularExpressions;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;
using System.Windows.Shapes;
using Path = System.IO.Path;

namespace AoYing_DeviceCollection
{
    public class SmtMachine_Gather
    {
        /// <summary>
        /// SPI采集状态
        /// </summary>
        public static bool spiState = true;
        /// <summary>
        /// AOI采集状态
        /// </summary>
        public static bool aoi2dState = true;
        /// <summary>
        /// AOI采集状态
        /// </summary>
        public static bool aoi3dState = true;
        /// <summary>
        /// feeder采集状态
        /// </summary>
        public static bool feederState = true;
        // 定义一个锁对象
        public static object lockObj = new object();
        /// <summary>
        /// feeder采集状态
        /// </summary>
        public static bool mkState = false;

        /// <summary>
        /// feeder采集状态
        /// </summary>
        public static bool portState = false;

        public static Dictionary<string, string> picKeyValue = new Dictionary<string, string>();

        #region 移动图片
        public static void PicMove()
        {
            while (true)
            {
                try
                {
                    if (picKeyValue.ToList().Count() > 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【图片转移】数量{picKeyValue.ToList().Count()}";
                    }


                    foreach (var item in picKeyValue.ToList())
                    {
                        string picFile = item.Key;
                        string moveFile = item.Value;
                        if ((File.GetAttributes(picFile) & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            //文件夹转移
                            CommonHelper.MoveFolder(picFile, moveFile);
                        }
                        else
                        {
                            //文件转移
                            // 检查目标文件夹中是否存在相同的文件
                            if (File.Exists(moveFile))
                            {
                                string dateNow = DateTime.Now.ToString("yyyyMMddHHmmss");
                                moveFile = $"{moveFile}-重复{dateNow}";

                            }
                            File.Move(picFile, moveFile);
                        }
                        // 移除已处理的项
                        picKeyValue.Remove(picFile);
                        Thread.Sleep(1000 * 2);
                    }
                }
                catch (Exception ex)
                {

                    BaseUtils._eventMsg.ErrorMsg = $"【图片转移出错】\n{ex.Message}";
                }

                Thread.Sleep(1000 * 2);
            }

        }
        #endregion

        #region SPI采集
        public static void SPI_GatherSmtMachine(string AcquisitionName)
        {

            while (spiState)
            {
                lock (lockObj)
                {
                    string tempfilename = string.Empty;
                    //当前日期到日 用于匹配当日生产的采集文件名 
                    string dateDay = DateTime.Now.ToString("yyyyMMdd");
                    try
                    {
                        //通过采集标识查询采集设备配置   FilePath 采集文件路径
                        DataTable configDt = CommonHelper.GetDataTable($"select DevicePath,ExpirePath,AreaName from sysdatmachine where MachName='SPI'");

                        for (int c = 0; c < configDt.Rows.Count; c++)
                        {
                            string path = configDt.Rows[c]["DevicePath"].ToString();
                            string areaName = configDt.Rows[c]["AreaName"].ToString();

                            DataTable wocodeDt = CommonHelper.GetDataTable($"select wocode,sfcno,ProductID,ProductName  from sfcdatwocode where AreaName='{areaName}' AND Status='6';");
                            //工单 
                            string wocode = string.Empty;
                            //指令单
                            string sfcno = string.Empty;
                            //产品id
                            string ProductID = string.Empty;
                            //产品名称
                            string ProductName = string.Empty;
                            if (wocodeDt.Rows.Count > 0)
                            {
                                wocode = wocodeDt.Rows[0][0].ToString();
                                sfcno = wocodeDt.Rows[0][1].ToString();
                                ProductID = wocodeDt.Rows[0][2].ToString();
                                ProductName = wocodeDt.Rows[0][3].ToString();
                            }

                            if (path == "")
                            {
                                continue;
                            }
                            if (!CommonHelper.IsServerConnected(path))
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】 网络错误或延迟超过500毫秒";
                                Thread.Sleep(1000 * 5 * 60);
                                continue;
                            }
                            //过期文件移动位置 有值则将采集过文件移动此文件夹下 无值则不处理
                            string expiredPath = configDt.Rows[c]["ExpirePath"].ToString();

                            List<string> filesNameTime;//存采集文件列表               
                            try
                            {
                                //获取文件夹下所有文件名
                                filesNameTime = CommonHelper.GetShareFiled(path, "*.csv");
                            }
                            catch (Exception ex)
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】\n{ex.Message}";
                                continue;
                            }

                            //读取采集记录表 用于对比现采集文件
                            // DataTable filelogdt = CommonHelper.GetDataTable($"select FileName from mainrecords ");
                            DataTable filelogdt = CommonHelper.GetDataTable($"select 1;");
                            List<string> serialDt = new List<string>();// CommonHelper.DataTableToList("FileName", filelogdt);
                            //读取采集记录表比对采集文件新增内容是否存在 
                            var diffFile = filesNameTime.Except(serialDt);
                            List<string> picList = new List<string>();
                            if (diffFile.Count() > 0)
                            {
                                BaseUtils._eventMsg.Info = $"【{AcquisitionName}采集开始】文件数{diffFile.Count()} ";
                            }

                            //循环未采集文件
                            foreach (var filename in diffFile)
                            {

                                try
                                {


                                    tempfilename = filename;
                                    MainModel main = new MainModel();
                                    DataTable screenDt = CommonHelper.CsvToDataTable(path + "\\" + filename);

                                    if (screenDt.Rows.Count < 4)
                                    {
                                        continue;
                                    }

                                    string picPath = string.Empty;

                                    StringBuilder stringBuildermain = new StringBuilder();
                                    StringBuilder stringBuilderdetail = new StringBuilder();
                                    //模组名字
                                    string ModelName = screenDt.Rows[1][0].ToString();
                                    //线体名字
                                    string LineNumber = screenDt.Rows[1][1].ToString();

                                    string BoardStatus = screenDt.Rows[2][1].ToString();
                                    string BoardBarcode = screenDt.Rows[2][3].ToString();
                                    //
                                    if (BoardBarcode == "")
                                    {
                                        string[] files = filename.Split('_');
                                        if (files.Length > 1)
                                        {
                                            BoardBarcode = files[1].Replace(".csv", "");
                                        }
                                        //过站 新增工艺流程
                                        //SendProcess(BoardBarcode, wocode,sfcno);
                                    }
                                    string guid = Guid.NewGuid().ToString();
                                    stringBuildermain.Append("insert into mainrecords(ModelName,LineNumber,BoardStatus,BoardBarcode,ArrayID,ArrayStatus,ArrayBarcode,FileName,FileDate,PicPath,Wocode) VALUE" +
                                                       $"({CommonHelper.GetKeys(ModelName)},{CommonHelper.GetKeys(LineNumber)},{CommonHelper.GetKeys(BoardStatus)},{CommonHelper.GetKeys(BoardBarcode)}," +
                                                       $"{CommonHelper.GetKeys(main.ArraylD)},{CommonHelper.GetKeys(main.ArrayStatus)},{CommonHelper.GetKeys(main.ArrayBarcode)},{CommonHelper.GetKeys(filename)}," +
                                                       $"'{dateDay}',{CommonHelper.GetKeys(picPath)},{CommonHelper.GetKeys(wocode)});");
                                    stringBuilderdetail.Append("insert into detailrecords(ModelName,LineNumber,BoardStatus,BoardBarcode,Wocode,PadID,ComponentID,Type,Area,Height,Volume,XOffset,YOffset,PadSizeX,PadSizeY,Area2,Height2,Volume2,Result,Errcode,PinNum,Barcode,Date,Time,ArrayID) values ");
                                    for (int i = 4; i < screenDt.Rows.Count; i++)
                                    {

                                        if (screenDt.Rows[i][0].ToString() == "")
                                        {
                                            continue;
                                        }
                                        //取子表所需字段
                                        string countStr = string.Empty;
                                        for (int j = 0; j < 20; j++)
                                        {
                                            countStr += "'" + screenDt.Rows[i][j].ToString() + "',";
                                        }
                                        if (countStr.Length == 0)
                                        {
                                            continue;
                                        }
                                        countStr = $"({CommonHelper.GetKeys(ModelName)},{CommonHelper.GetKeys(LineNumber)},{CommonHelper.GetKeys(BoardStatus)},{CommonHelper.GetKeys(BoardBarcode)},{CommonHelper.GetKeys(wocode)},{countStr.Substring(0, countStr.Length - 1)}),";
                                        if (i == screenDt.Rows.Count - 1)
                                        {
                                            countStr = countStr.Substring(0, countStr.Length - 1);
                                        }
                                        stringBuilderdetail.Append(countStr);
                                        //}

                                    }
                                    ProcessParameters process = new ProcessParameters();
                                    process.FinalResult = main.ArrayStatus == "OK" ? true : false;
                                    ///设备工艺流程过站
                                    ReturnMsg returnMsg = MachineProcess("14", BoardBarcode, process);
                                    if (returnMsg.Status == "1" || BoardBarcode.Contains("/"))
                                    {
                                        BaseUtils._eventMsg.Info = $"【记录并转移文件】SN【{BoardBarcode}】";
                                        if (stringBuildermain.Length > 0)
                                        {
                                            CommonHelper.ExeSql(stringBuildermain);
                                            if (stringBuilderdetail.Length > 0)
                                            {
                                                CommonHelper.ExeSql(stringBuilderdetail);
                                            }

                                        }
                                        //增加钢网刮刀数量
                                        SteelMeshScraper(wocode);


                                        #region 文件移动
                                        CommonHelper.MoveFileStr(path, expiredPath, filename);
                                        #endregion
                                    }
                                }
                                catch (Exception ex)
                                {
                                    BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错{tempfilename}】{ex.Message}";
                                    continue;
                                }
                            }


                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错{tempfilename}】{ex.Message}";
                        continue;
                    }
                    Thread.Sleep(1000 * 2);
                }

            }
        }


        class MainModel
        {

            public string ArraylD { get; set; }
            public string ArrayStatus { get; set; }
            public string ArrayBarcode { get; set; }


        }
        #endregion

        #region AOI采集程序

        //public static void AOI_SmtMachine(string AcquisitionName)
        //{
        //    while (aoiState)
        //    {
        //        lock (lockObj)
        //        {
        //            try
        //            {

        //                //通过采集标识查询采集设备配置   FilePath 采集文件路径
        //                DataTable configDt = CommonHelper.GetDataTable($"select DevicePath,ExpirePath,AreaName from sysdatmachine where MachName='AOI'");
        //                for (int i = 0; i < configDt.Rows.Count; i++)
        //                {
        //                    string path = configDt.Rows[i]["DevicePath"].ToString();
        //                    string areaName = configDt.Rows[i]["AreaName"].ToString();
        //                    if (path == "")
        //                    {
        //                        continue;
        //                    }
        //                    if (!CommonHelper.IsServerConnected(path))
        //                    {
        //                        BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】 网络错误或延迟超过500毫秒";
        //                        Thread.Sleep(1000 * 5 * 60);
        //                        continue;
        //                    }
        //                    //查询正在生产的工单
        //                    DataTable wocodeDt = CommonHelper.GetDataTable($"select wocode from sfcdatwocode where AreaName='{areaName}' AND Status='6';");
        //                    string wocode = string.Empty;
        //                    if (wocodeDt.Rows.Count > 0)
        //                    {
        //                        wocode = wocodeDt.Rows[0][0].ToString();

        //                    }
        //                    string expiredPath = configDt.Rows[i]["ExpirePath"].ToString();
        //                    //采集完成移动位置 有值则将采集过文件移动此文件夹下 无值则不处理
        //                    if (!string.IsNullOrEmpty(expiredPath))
        //                    {
        //                        if (!Directory.Exists(expiredPath))
        //                        {
        //                            //如果目标文件夹不存在则创建
        //                            Directory.CreateDirectory(expiredPath);
        //                        }

        //                    }
        //                    List<string> filesNameTime;//存采集文件列表               
        //                    try
        //                    {
        //                        //获取文件夹下所有文件名
        //                        filesNameTime = CommonHelper.GetShareFiled(path, "*.txt");
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】[未有采集文件]\n{ex.Message}";
        //                        Thread.Sleep(1000 * 60);
        //                        continue;
        //                    }
        //                    if (filesNameTime.Count > 0)
        //                    {
        //                        BaseUtils._eventMsg.Info = $"【{AcquisitionName}采集开始】文件数{filesNameTime.Count()} ";
        //                    }
        //                    foreach (var file in filesNameTime)
        //                    {

        //                        try
        //                        {
        //                            StringBuilder sqlBuilder = new StringBuilder();

        //                            string strLine;
        //                            //读文件流
        //                            FileStream fs = new FileStream(path + "\\" + file, FileMode.Open, FileAccess.ReadWrite);
        //                            StreamReader sr = new StreamReader(fs, Encoding.Default);
        //                            //aoi主表
        //                            sfcdatdevice_ay_aoi_Model model_main = new sfcdatdevice_ay_aoi_Model();
        //                            model_main.wocode = wocode;
        //                            bool isDetail = false;
        //                            string testResult = string.Empty;
        //                            bool split = false;
        //                            while ((strLine = sr.ReadLine()) != null)
        //                            {
        //                                string[] strLineLs = strLine.Split(':');
        //                                if (split)
        //                                {
        //                                    strLineLs = strLine.Split('=');

        //                                }
        //                                if (strLine.Contains("[DEFECT]"))
        //                                {
        //                                    isDetail = true;
        //                                    continue;
        //                                }

        //                                if (strLine.Contains("[PCB_INFO]"))
        //                                {
        //                                    split = true;
        //                                }
        //                                if (isDetail)
        //                                {

        //                                    if (strLineLs[0].Contains(";Count"))
        //                                    {
        //                                        continue;
        //                                    }
        //                                    if (strLineLs.Length > 1)
        //                                    {
        //                                        strLineLs = strLineLs[1].Split(',');
        //                                        sfcdatdevice_ay_aoidetail_Model detai = new sfcdatdevice_ay_aoidetail_Model
        //                                        {
        //                                            Array = strLineLs[0],
        //                                            Barcode = model_main.Barcode,
        //                                            REFID = strLineLs[1],
        //                                            TestResult = strLineLs[2],
        //                                            RepairResult = strLineLs[3],
        //                                            DefectCode = strLineLs[4]
        //                                        };
        //                                        sqlBuilder.Append(EntityHelper.GetInsertSQL(detai, "sfcdatdevice_ay_aoidetail"));
        //                                    }


        //                                }
        //                                else
        //                                {

        //                                    if (strLineLs[0].Contains("S/N"))
        //                                    {
        //                                        model_main.SN = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("Line"))
        //                                    {
        //                                        model_main.Line = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("Operator"))
        //                                    {
        //                                        model_main.OperatorID = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("Barcode"))
        //                                    {
        //                                        model_main.Barcode = strLineLs[1].Trim();
        //                                    }
        //                                    else if (strLineLs.Length > 1 && strLineLs[0].Contains("Inspect date"))
        //                                    {
        //                                        model_main.InspectDate = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("Inspection time"))
        //                                    {
        //                                        model_main.InspectionTime = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("Lot"))
        //                                    {
        //                                        model_main.LotNumber = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("szModelName"))
        //                                    {
        //                                        model_main.szModelName = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("Array"))
        //                                    {
        //                                        model_main.Array = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("iDefectCount"))
        //                                    {
        //                                        model_main.iDefectCount = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("iResultCount"))
        //                                    {
        //                                        model_main.iResultCount = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("TestResult"))
        //                                    {
        //                                        model_main.TestResult = strLineLs[1];
        //                                    }
        //                                    else if (strLineLs[0].Contains("RepairResult"))
        //                                    {
        //                                        model_main.RepairResult = strLineLs[1];
        //                                    }
        //                                }
        //                            }

        //                            sqlBuilder.Append(EntityHelper.GetInsertSQL(model_main, "sfcdatdevice_ay_aoi"));

        //                            fs.Close();
        //                            sr.Close();
        //                            string destinationFilePath = Path.Combine(expiredPath, file);
        //                            if (!string.IsNullOrEmpty(model_main.Barcode))
        //                            {
        //                                ProcessParameters process = new ProcessParameters();
        //                                if (model_main.TestResult == "NG")
        //                                {

        //                                    process.FinalResult = false;
        //                                }

        //                                //设备工艺流程过站
        //                                ReturnMsg returnMsg = MachineProcess("15", model_main.Barcode, process);
        //                                if (returnMsg.Status == "1" || file.Contains("_1_"))
        //                                {
        //                                    CommonHelper.ExeSql(sqlBuilder);
        //                                    if (File.Exists(destinationFilePath))
        //                                    {
        //                                        File.Delete(destinationFilePath);
        //                                    }

        //                                    //  移动文件
        //                                    File.Move(path + "\\" + file, expiredPath + "\\" + file);
        //                                }
        //                            }
        //                            else
        //                            {
        //                                CommonHelper.ExeSql(sqlBuilder);
        //                                if (File.Exists(destinationFilePath))
        //                                {
        //                                    File.Delete(destinationFilePath);
        //                                }

        //                                //移动文件
        //                                File.Move(path + "\\" + file, expiredPath + "\\" + file);

        //                            }

        //                        }
        //                        catch (Exception ex)
        //                        {

        //                            BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】{ex.Message}";
        //                            continue;
        //                        }



        //                    }
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】{ex.Message}";
        //                Thread.Sleep(1000 * 5);
        //                continue;
        //            }
        //            finally
        //            {
        //                Thread.Sleep(1000 * 5);
        //            }

        //        }
        //    }
        //}


        #endregion

        #region Feeder采集
        public static void Feeder_SmtMachine(string AcquisitionName)
        {
            while (feederState)
            {
                lock (lockObj)
                {
                    try
                    {

                        //通过采集标识查询采集设备配置   FilePath 采集文件路径
                        DataTable configDt = CommonHelper.GetDataTable($"select DevicePath,ExpirePath,AreaName from sysdatmachine where MachName='Feeder'");
                        for (int i = 0; i < configDt.Rows.Count; i++)
                        {
                            string path = configDt.Rows[i]["DevicePath"].ToString();
                            string areaName = configDt.Rows[i]["AreaName"].ToString();
                            if (string.IsNullOrEmpty(path))
                            {
                                continue;
                            }
                            if (!CommonHelper.IsServerConnected(path))
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】 网络错误或延迟超过500毫秒";
                                Thread.Sleep(1000 * 5 * 60);
                                continue;
                            }

                            string expiredPath = configDt.Rows[i]["ExpirePath"].ToString();
                            //采集完成移动位置 有值则将采集过文件移动此文件夹下 无值则不处理
                            if (!string.IsNullOrEmpty(expiredPath))
                            {
                                if (!Directory.Exists(expiredPath))
                                {
                                    //如果目标文件夹不存在则创建
                                    Directory.CreateDirectory(expiredPath);
                                }

                            }


                            List<string> filesNameTime;//存采集文件列表               
                            try
                            {
                                path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\Plot";


                                //获取文件夹下所有文件名
                                filesNameTime = CommonHelper.GetShareFiled(path, "*.dat");
                            }
                            catch (Exception ex)
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】[未有采集文件]\n{ex.Message}";
                                Thread.Sleep(1000 * 60);
                                continue;
                            }
                            if (filesNameTime.Count > 0)
                            {
                                BaseUtils._eventMsg.Info = $"【{AcquisitionName}采集开始】文件数{filesNameTime.Count()} ";
                            }
                            foreach (var file in filesNameTime)
                            {

                                try
                                {
                                    BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}  {file}进入解析】";
                                    StringBuilder sqlBuilder = new StringBuilder();
                                    List<string> feederSnList = new List<string>();
                                    string strLine;
                                    //读文件流
                                    FileStream fs = new FileStream(path + "\\" + file, FileMode.Open, FileAccess.ReadWrite);
                                    StreamReader sr = new StreamReader(fs, Encoding.Default);

                                    while ((strLine = sr.ReadLine()) != null)
                                    {

                                        if (strLine.IndexOf("MCNo") > -1 || strLine.IndexOf("PlotInfo") > -1)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            string[] value = strLine.Split(' ');
                                            if (value.Length > 6 && value[5].ToString().Replace("\"", "") != "")
                                            {
                                                string feederSN = value[5].Replace("\"", "");
                                                string qty = value[6];
                                                feederSnList.Add(feederSN);
                                                sqlBuilder.Append($"update sfcdat_feeder_info set PointQty=PointQty+{qty} where FEEDER_SN='{feederSN}';");
                                            }

                                        }


                                    }
                                    fs.Close();
                                    sr.Close();

                                    //是否获取到feeder
                                    if (feederSnList.Count > 0)
                                    {
                                        DataTable feederDt = CommonHelper.GetDataTable($"select FEEDER_SN from sfcdat_feeder_info where FEEDER_SN in ('{string.Join("','", feederSnList)}');");
                                        if (feederDt.Rows.Count == feederSnList.Count)
                                        {
                                            CommonHelper.ExeSql(sqlBuilder);
                                            //文件移动
                                            File.Move(path + "\\" + file, expiredPath + "\\" + file);
                                            BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}  {file}匹配成功】";
                                        }
                                        else
                                        {
                                            //List<string> feederDtList = feederDt.AsEnumerable()
                                            //                        .Select(s => s.Field<string>("FEEDER_SN"))
                                            //                        .ToList();

                                            List<string> resultList = feederDt.AsEnumerable()
                                          .Where(row => !feederSnList.Contains(row.Field<string>("FEEDER_SN")))
                                          .Select(row => row.Field<string>("FEEDER_SN"))
                                          .ToList();


                                            if (resultList.Count == 0)
                                            {
                                                CommonHelper.ExeSql(sqlBuilder);
                                                //文件移动
                                                File.Move(path + "\\" + file, expiredPath + "\\" + file);
                                                BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}  {file}匹配成功】";
                                            }
                                            else
                                            {
                                                BaseUtils._eventMsg.ErrorMsg = $"【{file}{AcquisitionName}采集SN未匹配成功】{string.Join(",", resultList)}";
                                            }

                                        }


                                    }
                                    else
                                    {
                                        //文件移动
                                        File.Move(path + "\\" + file, expiredPath + "\\" + file);
                                    }


                                }
                                catch (Exception ex)
                                {

                                    BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】{ex.Message}";
                                    continue;
                                }



                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{AcquisitionName}采集出错】{ex.Message}";
                        Thread.Sleep(1000 * 5);
                        continue;
                    }
                    finally
                    {
                        Thread.Sleep(1000 * 5);
                    }

                }
            }
        }

        #endregion

        #region        增加钢网刮刀数量    
        /// <summary>
        /// 增加钢网刮刀数量
        /// </summary>
        public static void SteelMeshScraper(string wocode)
        {
            try
            {
                //根据视图查找 reelid与设备类型
                DataTable fixreelid = CommonHelper.GetDataTable($"select ReelID,FixType from v_sfcdatmes_fix_vstorage where wocode='{wocode}';");
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < fixreelid.Rows.Count; i++)
                {
                    string reelid = fixreelid.Rows[i][0].ToString();
                    string FixType = fixreelid.Rows[i][1].ToString();
                    double useqty = 1;
                    if (FixType == "刮刀")
                    {
                        useqty = 0.5;
                    }
                    else if (FixType == "钢网")
                    {
                        useqty = 1;
                    }
                    stringBuilder.Append($"update sfcdatmes_fix_vstorage set UseQty=UseQty+{useqty} where ReelID='{reelid}';");
                }
                if (stringBuilder.Length > 0)
                {
                    CommonHelper.ExeSql(stringBuilder);
                }
            }
            catch (Exception ex)
            {

                BaseUtils._eventMsg.ErrorMsg = $"【SPI增加钢网/刮刀数量采集出错】{ex.Message}";
            }


        }
        #endregion

        #region 工艺流程
        /// <summary>
        /// 设备过站
        /// </summary>
        /// <param name="machid"></param>
        /// <param name="sn"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static ReturnMsg MachineProcess(string machid, string sn, ProcessParameters parameters)
        {
            ReturnMsg returnMsg = new ReturnMsg();
            returnMsg.Status = "0";
            try
            {


                BaseUtils._eventMsg.Info = $"【进入设备过站】SN【{sn}】";
                StringBuilder sql = new StringBuilder();

                List<string> sl = new List<string>();

                List<string> snList = new List<string>();
                // 获取工艺流程 
                DataTable processTable = CommonHelper.GetDataTable($"select vst.*,process.DesignJson from sfcdatmes_vstorage_producing vst join sfcdatwocode wo on vst.SFCNo = wo.SfcNo join sfcdatmesproduct pro on wo.AreaID=pro.AreaID and wo.ProductID=pro.ProductID join sfcdatmes_process process on pro.TechnologicalProcessID = Process.id where vst.SN = '{sn}';");

                if (processTable.Rows.Count == 0)
                {
                    processTable = CommonHelper.GetDataTable($"select vst.*,process.DesignJson from sfcdatmes_vstorage_producing vst join sfcdatwocode wo on vst.SFCNo = wo.SfcNo join sfcdatmesproduct pro on wo.AreaID=pro.AreaID and wo.ProductID=pro.ProductID join sfcdatmes_process process on pro.TechnologicalProcessID = Process.id where vst.boxno1 = '{sn}' or vst.boxno2 = '{sn}' or vst.boxno3 = '{sn}';");

                    if (processTable.Rows.Count == 0)
                    {
                        returnMsg._ReturnMsg = "[错误]未获取工艺流程";
                        BaseUtils._eventMsg.ErrorMsg = $"[错误]未获取工艺流程SN【{sn}】";
                        return returnMsg;
                    }
                    else
                    {
                        foreach (DataRow row in processTable.Rows)
                        {
                            sl.Add($"'{row["sn"].ToString()}'");

                            snList.Add($"'{row["sn"].ToString()}'");
                        }
                    }
                }
                else
                {
                    sl.Add($"'{processTable.Rows[0]["sn"].ToString()}'");

                    snList.Add(processTable.Rows[0]["sn"].ToString());

                    //return returnMsg;
                }

                string designJsonStr = processTable.Rows[0]["DesignJson"].ToString();

                DesignJson designJson = JsonConvert.DeserializeObject<DesignJson>(designJsonStr);

                Cells cell = null;

                foreach (Cells c in designJson.cells)
                {
                    if (c.data != null && !string.IsNullOrEmpty(c.data.machid) && c.data.machid.Equals(machid))
                    {
                        cell = c;

                        break;
                    }
                }
                if (cell == null)
                {
                    BaseUtils._eventMsg.ErrorMsg = $"[错误]无法根据设备ID[{machid}]找到工艺节点,请检查是否绑定";
                    return returnMsg;
                }

                //   BaseUtils._eventMsg.Info = $"SN【{sn}  生产过站 工序节点】";
                // 生产过站 工序节点
                sql.Append($"update sfcdatmes_vstorage_producing set ProcessType='process',ProcessID='{cell.id}',ProcessName='{cell.data.name}' where sn in ({string.Join(",", sl.ToArray())});");
                // AOI/Xray 检测结果Fail，记录NGProcess
                if (machid.Contains("AOI") || machid.Contains("Xray"))
                {
                    string ngProcess = machid.Contains("AOI") ? "AOI" : "Xray";
                    if ("FAIL".Equals(parameters.ArrayStatus.ToUpper()))
                    {
                        sql.Append($"update sfcdatmes_vstorage_producing set NGProcess='{ngProcess}' where sn in ({string.Join(",", sl.ToArray())});");
                    }
                }
                // 记录SN过站日志
                List<string> list = new List<string>();

                string ProcessID = cell.id;

                string ProcessName = cell.data.name;

                string ProcessType = cell.shape;

                string GXCode = cell.data.type;

                string MateID = processTable.Rows[0]["mateid"].ToString();

                string WOCode = processTable.Rows[0]["WOCode"].ToString();

                string SFCNo = processTable.Rows[0]["SFCNo"].ToString();

                sql.Append($"insert into sfcdatmes_sn_process_log (Creator,CreatorLoginID,WOCode,SFCNo,MateID,Qty,ProcessID,ProcessName,ProcessType,GXCode,sn,TestResult) values ");

                foreach (string _sn in snList)
                {
                    list.Add($"('{machid}','{machid}','{WOCode}','{SFCNo}','{MateID}',1,'{ProcessID}','{ProcessName}','{ProcessType}','{GXCode}','{_sn}','{parameters.TestResult}')");
                }
                sql.Append(string.Join(",", list.ToArray()));

                sql.Append(";");

                // 统计SN每个工位过站数量 sfcdatmes_sn_process_group

                int Qty = sl.Count;

                DataTable logTable = CommonHelper.GetDataTable($"select * from sfcdatmes_sn_process_log where sn in ({string.Join(",", sl.ToArray())}) and processid = '{cell.id}';");
                // 如果这个工序允许重复过站,需要看一下在这个工位是否有过站记录
                if (cell.data.isRepeat)
                {
                    foreach (string _sn in snList)
                    {
                        // 如果这个SN没有记录过,则看有没有记录过，没记录过，则记录下，有记录过则不管 logTable.Select($"sn='{sn}'").Length == 0
                        if (logTable.Rows.Count == 0 || (logTable.Rows.Count > 0 && logTable.Select($"sn='{_sn}'").Length == 0))
                        {
                            if (CommonHelper.GetDataTable($"select 1 from sfcdatmes_sn_process_group where sfcno='{SFCNo}' and processid='{ProcessID}';").Rows.Count == 0)
                            {
                                sql.Append($"insert into sfcdatmes_sn_process_group (Creator,CreatorLoginID,WOCode,SFCNo,MateID,Qty,ProcessID,ProcessName,ProcessType,GXCode) values ");

                                sql.Append($"('{machid}','{machid}','{WOCode}','{SFCNo}','{MateID}',{Qty},'{ProcessID}','{ProcessName}','{ProcessType}','{GXCode}');");
                            }
                            else
                            {
                                sql.Append($"update sfcdatmes_sn_process_group set qty=qty+{Qty} where sfcno='{SFCNo}' and processid='{ProcessID}';");
                            }
                        }
                    }
                }
                else
                {
                    if (CommonHelper.GetDataTable($"select 1 from sfcdatmes_sn_process_group where sfcno='{SFCNo}' and processid='{ProcessID}';").Rows.Count == 0)
                    {
                        sql.Append($"insert into sfcdatmes_sn_process_group (Creator,CreatorLoginID,WOCode,SFCNo,MateID,Qty,ProcessID,ProcessName,ProcessType,GXCode) values ");

                        sql.Append($"('{machid}','{machid}','{WOCode}','{SFCNo}','{MateID}',{Qty},'{ProcessID}','{ProcessName}','{ProcessType}','{GXCode}');");

                    }
                    else
                    {
                        sql.Append($"update sfcdatmes_sn_process_group set qty=qty+{Qty} where sfcno='{SFCNo}' and processid='{ProcessID}';");
                    }
                }

                // 测试结果不OK，并且需要自动报修
                if (machid == "15" && !parameters.FinalResult && parameters.isAutoInRepairRoom)
                {
                    BaseUtils._eventMsg.Info = $"{machid}sn 进入自动报修";
                    string NowBoxNoLevel = processTable.Rows[0]["NowBoxNoLevel"].ToString();

                    string SNType = processTable.Rows[0]["SNType"].ToString();


                    string guid = Guid.NewGuid().ToString();

                    sql.Append($"insert into sfcdatmes_repair_room (RepairCode,Guid,Creator,CreatorLoginID,WOCode,SFCNo,SN,SNType,ProcessID,ProcessName,ProcessType,MateID,_Status,remark) ");
                    string dateTime = DateTime.Now.ToString("yyyymmddHHmmss");
                    string RepairCode = "BX" + dateTime;
                    string RepairCode2 = "WX" + dateTime;// GETBUSINO("172.27.32.57:86", "维修单号");
                    if ("0".Equals(NowBoxNoLevel))
                    {
                        // sql.Append($"select '{guid}','{machid}','{machid}','{WOCode}','{SFCNo}','{sn}','{SNType}','{ProcessID}','{ProcessName}','{ProcessType}','{MateID}','报修','拼版码 {repairList.FirstOrDefault()?.ArraySN},设备ID{machid}自动报修';");
                        sql.Append($"select  '{RepairCode}','{guid}','{machid}','{machid}','{WOCode}','{SFCNo}','{sn}','{SNType}','{ProcessID}','{ProcessName}','{ProcessType}','{MateID}','报修','设备ID{machid}自动报修';");

                        sql.Append($"update sfcdatmes_vstorage_producing set _Status2='维修' where sn='{sn}';");
                    }
                    else
                    {
                        SNType = $"BOX{NowBoxNoLevel}";

                        sql.Append($"select 'RepairCode','{guid}','{machid}','{machid}',a.WOCode,a.SFCNo,a.SN,a.SNType,a.ProcessID,a.ProcessName,a.ProcessType,a.MateID,'报修' from sfcdatmes_vstorage_producing a where a.boxno{NowBoxNoLevel}='{sn}';");

                        sql.Append($"update sfcdatmes_vstorage_producing set _Status2='维修' where boxno{NowBoxNoLevel}='{sn}';");
                    }

                    //string detailGuid = string.Empty;
                    string detailGuid = Guid.NewGuid().ToString();
                    // 存维修明细
                    sql.Append($"insert into sfcdatmes_repair_room_detail (Guid,RepairCode,RepairCode2,SN,SFCNo) " +
                        $"values ('{guid}','{RepairCode}', '{RepairCode2}', '{sn}', '{WOCode}');");
                    //if (repairList != null)
                    //{
                    //    foreach (var detail in repairList)
                    //    {
                    //        detailGuid = Guid.NewGuid().ToString();

                    //        // 存维修明细
                    //        sql.Append($"insert into sfcdatmes_repair_room_detail (Guid, creator, BadCode, BadReason, _Desc, DetailGuid) values ('{guid}', '{creator}', '{detail.BadCode}', '{detail.BadReason}', '{detail._Desc}', '{detailGuid}');");

                    //        foreach (var point in detail.PointList)
                    //        {
                    //            // 存维修点位明细
                    //            sql.Append($"insert into sfcdatmes_repair_room_point_detail (Guid, creator, Point, MateID, DetailGuid) values ('{guid}', '{creator}', '{point}', '{MateID}', '{detailGuid}');");
                    //        }
                    //    }
                    //}
                }


                CommonHelper.ExeSql(sql);


                returnMsg.item = new
                {
                    WOCode = WOCode,
                    SFCNo = SFCNo,
                    // 这里的MATEID 等于 PRODUCTID
                    MateID = MateID,
                    ProcessID = ProcessID,
                    ProcessName = ProcessName,
                    ProcessType = ProcessType
                };
                BaseUtils._eventMsg.Info = $"【过站成功】SN【{sn}】";
                returnMsg.Status = "1";
            }
            catch (Exception ex)
            {

                BaseUtils._eventMsg.ErrorMsg = $" 【{machid}】【SN{sn}】过站报错【{ex.Message}】";
            }
            return returnMsg;

        }

        #endregion

        #region 定义返回


        public class linkSNListModel
        {
            public string showname { get; set; }
            public bool disabled { get; set; } = true;
            public string realsn { get; set; }
            public string value { get; set; }
        }
        #endregion

        #region FCT 采集
        public static string FCT_GatherSmtMachine(string mainSN, string linkSN, string deviceId)
        {

            string messreturn = "执行成功";
            lock (lockObj)
            {
                try
                {
                    // 获取所有相关数据
                    DataSet dataSet = CommonHelper.GetDataSet($@"
                                       select DeviceType, DeviceName, DeviceModel, CollectPath, TransferPath,AreaID,DeviceName,deviceId  from deviceparameter where deviceId='{deviceId}';               
                                       select mainsn from sfcdatlinksn where linksn='{mainSN}';
                                       select linkSN from sfcdatlinksn where linksn='{linkSN}';");


                    // 从 DataSet 中获取对应的 DataTable
                    DataTable configDt = dataSet.Tables[0]; // 设备配置表
                    DataTable mainLogDt = dataSet.Tables[1]; // link 关联表
                    DataTable linkLogDt = dataSet.Tables[2]; // link 关联表

                    if (configDt.Rows.Count <= 0 || string.IsNullOrEmpty(configDt.Rows[0]["CollectPath"].ToString()))
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】采集路径为空";

                        return $"【{deviceId}采集出错】采集路径为空";
                    }

                    if (mainLogDt.Rows.Count <= 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】该SN【{mainSN}】无主板码关联";
                        return $"【{deviceId}采集出错】该SN【{mainSN}】无主板码关联";
                    }
                    if (linkLogDt.Rows.Count > 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】该linkSN【{linkSN}】已关联主板SN";
                        return $"【{deviceId}采集出错】该linkSN【{linkSN}】已关联主板SN";
                    }

                    string oldMain = mainLogDt.Rows[0][0].ToString();
                    DataTable wocodeDt = CommonHelper.GetDataTable($"select WOCode, SFCNo, mateid from sfcdatmes_sn_process_log WHERE LinkSN = '{oldMain}' or SN = '{oldMain}' ORDER BY id Desc LIMIT 1;");
                    if (wocodeDt.Rows.Count <= 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】未找到SN关联数据{mainSN}";
                        return $"【{deviceId}采集出错】未找到SN关联数据{mainSN}";
                    }
                    BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】原始SN【{oldMain}】";

                    //采集路径
                    string collectPath = configDt.Rows[0]["CollectPath"].ToString();
                    //转移后路径
                    string transferPath = configDt.Rows[0]["TransferPath"].ToString();

                    string DeviceName = configDt.Rows[0]["DeviceName"].ToString();
                    //工单
                    string wocode = wocodeDt.Rows[0]["wocode"].ToString();

                    string mateid = wocodeDt.Rows[0]["mateid"].ToString();
                    //制令单
                    string sfcno = wocodeDt.Rows[0]["sfcno"].ToString();
                    DataTable wocodT = CommonHelper.GetDataTable($"select AreaID,ProductID,productName from sfcdatWocode where sfcno='{sfcno}';");
                    if (wocodT.Rows.Count <= 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】无工单信息";
                        return $"【{deviceId}采集出错】无工单信息";
                    }
                    string areaID = wocodT.Rows[0]["areaID"].ToString();
                    string productID = wocodT.Rows[0]["ProductID"].ToString();

                    string productName = wocodT.Rows[0]["productName"].ToString();
                    DateTime currentDate = DateTime.Now;

                    // 获取当前月和当前天
                    string currentMonth = currentDate.ToString("yyyyMM");  // 年月格式
                    string currentDay = currentDate.ToString("dd");        // 日格式

                    transferPath = Path.Combine(transferPath, currentMonth, currentDay);

                    if (!CommonHelper.IsServerConnected(collectPath))
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】 网络错误或延迟超过500毫秒";
                        return $"【{deviceId}采集出错】 网络错误或延迟超过500毫秒";
                    }
                    FileInfo fileInfo = null;

                    DirectoryInfo rootDir = new DirectoryInfo($@"{collectPath}");
                    var allPassFolders = rootDir.GetDirectories("*", SearchOption.AllDirectories)
                                               .Where(dir => dir.Name.Equals("PASS", StringComparison.OrdinalIgnoreCase));
                    foreach (var item in allPassFolders)
                    {
                        //获取最早的文件信息
                        fileInfo = GetEarliestCreatedFile(item.FullName, "*.csv");
                        if (fileInfo != null)
                        {
                            BaseUtils._eventMsg.Info = $"【路径{item.FullName}】";
                            // 获取当前文件的父级目录
                            DirectoryInfo parentDirectory = item.Parent;

                            // 获取再上一层的文件夹的名称
                            string lastFolderName = parentDirectory.Name;
                            transferPath = Path.Combine(transferPath, lastFolderName);
                            break;
                        }
                    }

                    if (fileInfo == null)
                    {

                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】 未有采集文件";
                        return $"【{deviceId}采集出错】 未有采集文件";
                    }
                    DataTable screenDt = CommonHelper.CsvToDataTable(fileInfo.FullName);
                    string guid = Guid.NewGuid().ToString();
                    StringBuilder stringBuildermain = new StringBuilder();
                    //  string barCode = screenDt.Rows[13][0].ToString();

                    string creator = screenDt.Rows[3][0].ToString().ToString().Split(':')[1];
                    string ProgramName = screenDt.Rows[0][0].ToString().ToString().Split(':')[1];
                    string testResult = screenDt.Rows[4][0].ToString().Split(':')[1];
                    string testDateTime = screenDt.Rows[6][0].ToString();
                    for (int i = 8; i < screenDt.Rows.Count; i++)
                    {

                        if (string.IsNullOrEmpty(screenDt.Rows[i][0].ToString()))
                        {
                            break;
                        }
                        if (screenDt.Rows[i][6].ToString() != "PASS")
                        {
                            stringBuildermain.Append("insert into sfcdatdevice_fctelectricaltestRecords(ProductSN,TestItem,TestVI,Low_L,Meas_L,High_L) values" +
                          $"('{linkSN}','{screenDt.Rows[i][1]}','{screenDt.Rows[i][5]}','{screenDt.Rows[i][2]}','{screenDt.Rows[i][5]}','{screenDt.Rows[i][3]}');");

                        }

                    }
                    //是否过站
                    string isProcess = "0";
                    //失败信息
                    string failReason = "";

                    #region 过站


                    if (testResult == "PASS")
                    {


                        //过站方法
                        var result = SendProcess(configDt, oldMain, wocode, sfcno, mateid, linkSN);
                        BaseUtils._eventMsg.ErrorMsg = $"过站返回值 result {result}";
                        if (result != null)
                        {
                            JObject jsonObject = JObject.Parse(result);
                            // 获取status值
                            string status = jsonObject["status"].Value<string>();
                            //0执行失败 1执行成功
                            if (status == "1")
                            {
                                BaseUtils._eventMsg.Info = $"SN【{linkSN}】【过站成功】{result}";
                                isProcess = "1";
                            }
                            else
                            {
                                isProcess = "2";
                                failReason = jsonObject["_ReturnMsg"].Value<string>();
                            }
                        }
                    }

                    #endregion

                    stringBuildermain.Append($"insert into sfcdatdevice_fctelectricalmain(WoCode,SFCNo,BarCode,TestResult,TestDateTime,MachCode,IsProcess,FailReason,CreateTime,UpdateTime,creator,areaID,productId,productName,MachName,ProgramName)values" +
                        $"('{wocode}','{sfcno}','{linkSN}','{testResult}','{testDateTime}','{deviceId}','{isProcess}','{failReason}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{creator}','{areaID}','{productID}','{productName}','{DeviceName}','{ProgramName}')");

                    CommonHelper.ExeSql(stringBuildermain);
                    BaseUtils._eventMsg.Info = $"SN【{linkSN}】【采集完成】";
                    // 移动文件
                    FileMove(transferPath, fileInfo);


                }
                catch (Exception ex)
                {
                    BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】{ex.Message}";

                    return $"【{deviceId}采集出错】{ex.Message}";
                }

            }

            return messreturn;
        }
        #endregion

        static object SendProcessLock = new object();
        public static string SendProcess(DataTable deviceDT, string sn, string wocode, string sfcno, string productID, string linkSn = null)
        {
            lock (SendProcessLock)
            {
                try
                {
                    string arealD = deviceDT.Rows[0]["AreaID"].ToString();
                    string deviceName = deviceDT.Rows[0]["DeviceName"].ToString();
                    string deviceId = deviceDT.Rows[0]["deviceId"].ToString();
                    //根据产品找到工艺流程id
                    DataTable processeDt = CommonHelper.GetDataTable($"select DesignJson from sfcdatmes_process a JOIN v_sfcdatmesproduct b  on a.id=b.TechnologicalProcessID where b.ProductID ='{productID}' AND  a.IsEnable='1'; ");

                    if (processeDt.Rows.Count <= 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"设备[{deviceName}],sn:[{sn}]对应的产品ID[{productID}]工艺流程信息未维护";
                        return JsonConvert.SerializeObject(new ReturnMsg
                        {
                            Status = "0",
                            _ReturnMsg = $"设备[{deviceName}],sn:[{sn}]对应的产品ID[{productID}]工艺流程信息未维护"
                        });
                    }

                    // 解析 JSON
                    JObject cellobj = JObject.Parse(processeDt.Rows[0]["DesignJson"].ToString());

                    // 提取 cells 数组
                    JArray cellsArray = (JArray)cellobj["cells"];

                    // 用于存储满足条件的 JSON 元素
                    List<JToken> result = new List<JToken>();

                    // 遍历 cells 数组
                    foreach (JObject item in cellsArray)
                    {
                        // 检查 zIndex 是否为 "1" 开头节点
                        if (item["data"] != null)
                        {
                            if (item["data"]["machid"]?.Type == JTokenType.String)
                            {
                                if (item["data"]["machid"].ToString() == deviceId)
                                {
                                    result.Add(item);
                                }
                            }
                        }
                    }

                    if (result.Count == 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"设备[{deviceName}]设备ID未维护至工艺流程";
                        return JsonConvert.SerializeObject(new ReturnMsg
                        {
                            Status = "0",
                            _ReturnMsg = $"设备[{deviceName}]设备ID未维护至工艺流程"
                        }); ;

                    }

                    // 将结果转换为 JSON 
                    string resultJson = JsonConvert.SerializeObject(result[0], Formatting.Indented);


                    #region  拼接json

                    var sendModel = new
                    {
                        funcname = "Process",
                        body = new
                        {
                            sn = sn,
                            snlist = new string[] { sn },
                            boxno = "",
                            areaid = arealD,
                            sfcno = sfcno,
                            wocode = wocode,
                            productid = productID,
                            mode = "工单模式",
                            gxcode = "",
                            boxcount = 0,
                            cell = result[0],
                            pcbaList = new object[] { },
                            linkListList = new object[] { },
                            isUnfinishBox = false,
                            isMixBox = false,
                            jumpCheck = false,
                            linkSNList = !string.IsNullOrWhiteSpace(linkSn) ? new List<linkSNListModel>()
                            {
                                new linkSNListModel {
                                 showname="LinkSN1",
                                 disabled=true,
                                 realsn=linkSn,
                                 value=linkSn,
                        } } : new List<linkSNListModel>() { },
                            fqcBadCode = "",
                            FQCList = new object[] { }
                        }
                    };

                    #endregion
                    //发送数据

                    var sendJson = JsonConvert.SerializeObject(sendModel);

                    //获取企业信息IP 地址
                    DataTable hostTable = CommonHelper.GetDataTable("SELECT hosturl,companyID from sysdatcompany limit 1;");

                    if (hostTable.Rows.Count == 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"企业信息未维护";
                        return JsonConvert.SerializeObject(new ReturnMsg
                        {
                            Status = "0",
                            _ReturnMsg = $"企业信息未维护"
                        });

                    }


                    string hostPath = hostTable.Rows[0]["hosturl"].ToString();
                    string dbname = hostTable.Rows[0]["companyID"].ToString();
                    //  BaseUtils._eventMsg.ErrorMsg = $"deviceName{deviceName}hostPath{hostPath} dbname{dbname}";

                    return HttpHelper.HttpPost($"http://{hostPath}/extend/invoke/?id=DefaultAllMethod&token={dbname}12345678", sendJson);


                }
                catch (Exception ex)
                {
                    BaseUtils._eventMsg.ErrorMsg = ($"发送过站报错【sn:{sn},{ex.ToString()}】");

                    return JsonConvert.SerializeObject(new ReturnMsg
                    {
                        Status = "0",
                        _ReturnMsg = ex.Message,
                    }); ;
                }
            }
        }



        /// <summary>
        /// 文件转移
        /// </summary>
        /// <param name="moveToPath">转移地址</param>
        /// <param name="file">文件</param>
        public static void FileMove(string moveToPath, FileInfo file)
        {
            // 如果目标目录不存在，则创建
            if (!Directory.Exists(moveToPath))
            {
                Directory.CreateDirectory(moveToPath);
            }

            // 设置目标文件的初始路径
            string destinationFile = Path.Combine(moveToPath, file.Name);

            // 检查目标文件是否存在
            if (File.Exists(destinationFile))
            {
                // 如果目标文件存在，生成一个新的文件名
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.Name);
                string fileExtension = Path.GetExtension(file.Name);

                // 生成当前时间的字符串格式：yyyyMMddHHmmss
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");

                // 创建新的文件名
                destinationFile = Path.Combine(moveToPath, $"{fileNameWithoutExtension}_{timestamp}{fileExtension}");
            }

            // 移动文件到目标位置
            file.MoveTo(destinationFile);
        }
        /// <summary>
        /// 获取路径文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static FileInfo[] GetExcelDicList(string path, string fileType)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            return root.GetFiles(fileType, SearchOption.TopDirectoryOnly);
        }
        public static FileInfo GetEarliestCreatedFile(string path, string fileType)
        {
            DirectoryInfo root = new DirectoryInfo(path);

            // 获取所有指定类型的文件
            FileInfo[] files = root.GetFiles(fileType, SearchOption.TopDirectoryOnly);

            // 如果没有找到文件，则返回 null
            if (files.Length == 0)
                return null;

            // 排序并返回创建时间最早的文件
            return files.OrderBy(f => f.CreationTime).First();
        }



        #region 锦飞
        #region 锦飞 SPI
        public static void JF_SPI_GatherSmtMachine(DataRow dataRow, string SfcNo)
        {
            //while (spiState)

            {
                lock (lockObj)
                {
                    try
                    {
                        // 初始化参数
                        var devicePath = dataRow["CollectPath"].ToString();
                        var expirePath = dataRow["TransferPath"].ToString();
                        var userName = dataRow["userName"].ToString();
                        var passWord = dataRow["passWord"].ToString();
                        var deviceId = dataRow["DeviceId"].ToString();
                        var deviceName = dataRow["DeviceName"].ToString();
                        var dateDay = DateTime.Now.ToString("yyyyMMdd");
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }

                        // 获取并处理CSV文件
                        var fileList = BaseUtils.GetExcelDicList(devicePath, "*.csv");
                        BaseUtils._eventMsg.Info = $"本次检查到{fileList.Length}数据";
                        if (!fileList.Any()) return;

                        var movePath = Path.Combine(expirePath, dateDay);
                        foreach (var file in fileList)
                        {
                            Thread.Sleep(3000);
                            ProcessCsvFile(file, movePath, SfcNo, deviceId, deviceName, dataRow);
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                        Thread.Sleep(2000);
                    }
                    Thread.Sleep(2000);
                }
            }
        }

        private static void ProcessCsvFile(FileInfo file, string movePath, string SfcNo, string deviceId, string deviceName, DataRow dataRow)
        {
            try
            {
                var infoDt = BaseUtils.CsvToDataTable(file.FullName);
                if (infoDt.Rows.Count <= 0)
                {
                    BaseUtils._eventMsg.Info = $"【文件为空】{file.Name}";
                    return;
                }

                // 解析CSV数据
                var recipeName = infoDt.Rows[1][0].ToString();
                var line = infoDt.Rows[1][1].ToString();
                var result = infoDt.Rows[2][1].ToString();
                var barcode = infoDt.Rows[2][3].ToString();
                var guid = Guid.NewGuid().ToString();

                // 获取工单信息
                DataTable wocodeDt = new DataTable();
                if (deviceId.ToUpper().EndsWith("-T"))
                {
                    wocodeDt = CommonHelper.GetDataTable($@"
                                                                                   SELECT 
                                                                                       sfcdatwocode.WOCode,
                                                                                       sfcdatwocode.SfcNo,
                                                                                       sfcdatwocode.ProductID,
                                                                                       sfcdatwocode.ProductName,
                                                                                       sfcdatmes_vstorage_producing.SN
                                                                                   FROM 
                                                                                       sfcdatwocode
                                                                                   JOIN 
                                                                                       sfcdatmes_vstorage_producing ON sfcdatwocode.SfcNo = sfcdatmes_vstorage_producing.SFCNo
                                                                                   WHERE 
                                                                                       sfcdatmes_vstorage_producing.SN='{barcode}';
                                                                                   ");
                }
                else
                {
                    wocodeDt = CommonHelper.GetDataTable($"select WOCode, SFCNo, areaID, ProductID, productName from sfcdatwocode WHERE SfcNo = '{SfcNo}' ORDER BY id Desc LIMIT 1;");
                }
                if (wocodeDt.Rows.Count <= 0)
                {
                    BaseUtils._eventMsg.ErrorMsg = $"【采集出错】未找到SN关联数据{barcode}";
                    return;
                }

                var wocode = wocodeDt.Rows[0]["WOCode"].ToString();
                var productId = wocodeDt.Rows[0]["ProductID"].ToString();
                SfcNo = wocodeDt.Rows[0]["SfcNo"].ToString();
                var mateid = productId;

                // 构建SQL语句
                var sqlBuilder = new StringBuilder();
                var keyValuePairs = ParseArrayInfo(infoDt, sqlBuilder, barcode);
                ParseDefectInfo(infoDt, sqlBuilder, keyValuePairs, wocode, SfcNo, recipeName, result, deviceId, deviceName, barcode, guid, line, mateid);

                // 处理过站逻辑
                if (result != "NG")
                {
                    ProcessStation(dataRow, keyValuePairs, wocode, SfcNo, mateid, barcode, line, mateid, recipeName, result, deviceId, deviceName, guid, ref sqlBuilder);
                }

                // 执行SQL并移动文件
                CommonHelper.ExeSql(sqlBuilder);
            }
            catch (Exception ex)
            {

                BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex}";
            }
            finally
            {

                FileMove(movePath, file);
            }


        }

        private static Dictionary<string, string> ParseArrayInfo(DataTable infoDt, StringBuilder sqlBuilder, string barcode)
        {
            var keyValuePairs = new Dictionary<string, string>();

            // 提前获取数据
            DataTable bigable = CommonHelper.GetDataTable($"SELECT pcbcode from zzdtrs_bigpcbtopcb WHERE bigpcb in (select bigpcb from zzdtrs_bigpcbtopcb where pcbcode='{barcode}');");
            var existingArrayIds = new HashSet<string>();
            foreach (DataRow row in bigable.Rows)
            {
                existingArrayIds.Add(row["pcbcode"].ToString());
            }
            for (int i = 3; i < infoDt.Rows.Count; i++)
            {
                if (infoDt.Rows[i][0].ToString().ToUpper() == "ARRAYID")
                {
                    var arrayId = infoDt.Rows[i][5].ToString();
                    keyValuePairs.Add(arrayId, infoDt.Rows[i][1].ToString());
                }
                else if (infoDt.Rows[i][0].ToString().ToUpper() == "PADID")
                {
                    break;
                }
            }
            // 判断是否已经存在
            if (keyValuePairs != null && keyValuePairs.Count > 0)
            {
                foreach (var item in keyValuePairs)
                {
                    if (!existingArrayIds.Contains(item.Value))
                    {
                        sqlBuilder.Append($"insert into zzdtrs_bigpcbtopcb (bigpcb,pcbcode,creator) values('{barcode}','{item.Key}','SPI采集'); " +
                            $"INSERT INTO `sfcdat_process_snbind` (`BigPCb`, `SN`,`BindQty`, `WoCode`, `SfcNo`, `ProcessId`, `ProcessName`, `Type`, `CreateTime`, `Creator`, `UpdateTime`) VALUES " +
                            $"('{barcode}', '{item.Key}',{keyValuePairs.Count}, NULL, NULL, NULL, NULL, NULL, CURRENT_TIMESTAMP(), 'SPI采集', CURRENT_TIMESTAMP());");
                    }
                }
            }

            return keyValuePairs;
        }


        private static void ParseDefectInfo(DataTable infoDt, StringBuilder sqlBuilder, Dictionary<string, string> keyValuePairs,
            string wocode, string sfcno, string recipeName, string result, string deviceId, string deviceName, string barcode, string guid, string line, string productId)
        {
            //可以获取详细测试数据的标记点
            int detaillabel = 10000000;
            for (int i = 0; i < infoDt.Rows.Count; i++)
            {
                if (infoDt.Rows[i][0].ToString().ToUpper() == "PADID")
                {
                    detaillabel = i;
                }
                if (i > detaillabel && infoDt.Rows[i][13].ToString().ToUpper() != "GOOD")
                {
                    var itembarcode = infoDt.Rows[i][16].ToString();
                    var panelSequence = keyValuePairs.ContainsKey(itembarcode) ? keyValuePairs[itembarcode] : string.Empty;

                    sqlBuilder.Append("insert into sfcdatdevice_jfspi_details(Wocode,SFCNO,AreaId,Product,RecipeName,Result,DeviceId,DeviceName,BarCode,Guid,panel_sequence,position,area,height,volume,x_offset,y_offset,defect_code)");
                    sqlBuilder.Append($"values('{wocode}','{sfcno}','{line}','{productId}','{recipeName}','{result}','{deviceId}','{deviceName}','{barcode}','{guid}','{panelSequence}','{infoDt.Rows[i][0]}','{infoDt.Rows[i][3]}','{infoDt.Rows[i][4]}','{infoDt.Rows[i][5]}','{infoDt.Rows[i][6]}','{infoDt.Rows[i][7]}','{infoDt.Rows[i][14]}');");
                }
            }
        }

        private static void ProcessStation(DataRow dataRow, Dictionary<string, string> keyValuePairs, string wocode, string sfcno, string mateid, string barcode, string line, string productId, string recipeName, string result, string deviceId, string deviceName, string guid, ref StringBuilder sqlBuilder)
        {
            var isProcess = "0";
            var failReason = string.Empty;
            DataTable newTable = dataRow.Table.Clone();

            // 将 DataRow 添加到新的 DataTable 中
            newTable.ImportRow(dataRow);

            foreach (var item in keyValuePairs)
            {
                BaseUtils._eventMsg.Info = $"SN【{item.Key}】【开始过站】";
                var resultJson = SendProcess(newTable, item.Key, wocode, sfcno, mateid);
                if (resultJson != null)
                {
                    var jsonObject = JObject.Parse(resultJson);
                    var status = jsonObject["status"].Value<string>();
                    if (status == "1")
                    {
                        BaseUtils._eventMsg.Info = $"SN【{item.Key}】【过站成功】{resultJson}";
                        new LogHelper().Info($"SN【{item.Key}】【过站成功】{resultJson}");
                        isProcess = "1";
                    }
                    else
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"SN【{item.Key}】【过站失败】{resultJson}";
                        new LogHelper().Error($"SN【{item.Key}】【过站失败】{resultJson}");
                        isProcess = "2";
                        failReason = jsonObject["_returnmsg"]?.Value<string>() ?? string.Empty;
                    }
                }
            }

            sqlBuilder.Append("insert into sfcdatdevice_jfspi(Wocode,SFCNO,AreaId,Product,RecipeName,Result,DeviceId,DeviceName,BarCode,Guid,isProcess,failReason)");
            sqlBuilder.Append($"values('{wocode}','{sfcno}','{line}','{productId}','{recipeName}','{result}','{deviceId}','{deviceName}','{barcode}','{guid}','{isProcess}','{failReason}');");
        }
        #endregion
        #region 锦飞MK
        public static void JF_MK_GatherSmtMachine(DataRow dataRow, string sfcno)
        {
            while (mkState)
            {
                lock (lockObj)
                {
                    try
                    {
                        // 初始化参数
                        var devicePath = dataRow["CollectPath"].ToString();
                        string expirePath = dataRow["TransferPath"].ToString();
                        var userName = dataRow["userName"].ToString();
                        var passWord = dataRow["passWord"].ToString();
                        var deviceId = dataRow["DeviceId"].ToString();
                        var deviceName = dataRow["DeviceName"].ToString();


                        BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";

                        DataTable wocodekdt = CommonHelper.GetDataTable($"select * from sfcdatwocode where sfcno='{sfcno}';");
                        if (wocodekdt.Rows.Count <= 0)
                        {
                            BaseUtils._eventMsg.Info = $"无制令单数据{sfcno}";
                            continue;
                        }
                        string productID = wocodekdt.Rows[0]["productID"].ToString();
                        string productName = wocodekdt.Rows[0]["ProductName"].ToString();
                        string wocode = wocodekdt.Rows[0]["wocode"].ToString();
                        string areaID = wocodekdt.Rows[0]["AreaID"].ToString();
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }

                        DateTime currentDate = DateTime.Now;
                        string formattedDate = currentDate.ToString("yyyy-yy-MM");

                        ///根据产品名称和当前月份 拼接新路径
                        devicePath = Path.Combine(devicePath, productName, formattedDate);
                        // 获取采集文件
                        FileInfo sourceFile = BaseUtils.GetExcelDicListMK(devicePath, "*.xls");
                        if (sourceFile == null)
                        {
                            BaseUtils._eventMsg.Info = $"未找到采集文件{devicePath}";
                            continue;

                        }

                        // 比较文件最后修改时间
                        DataTable fctelecTable = CommonHelper.GetDataTable($"select FileUpdateTime,RowIndex from  sfcdatdevice_fctelectricalmain where MONTH(FileUpdateTime) = MONTH(CURRENT_DATE)  AND YEAR(FileUpdateTime) = YEAR(CURRENT_DATE)AND productName='{productName}'  AND RowIndex IS NOT NULL ORDER BY id DESC LIMIT 1");
                        //文件最后记录行数
                        int rowIndex = 1;
                        if (fctelecTable.Rows.Count > 0)
                        {
                            //文件最后修改时间
                            DateTime fileUpdateTime = DateTime.Parse(fctelecTable.Rows[0]["FileUpdateTime"].ToString());
                            if (fileUpdateTime.Minute == sourceFile.LastWriteTime.Minute)
                            {
                                continue;
                            }
                            rowIndex = int.Parse(fctelecTable.Rows[0]["RowIndex"].ToString());
                        }
                        //拼接文件转移后路径
                        expirePath = Path.Combine(expirePath, productName, formattedDate);

                        //先将文件复制到指定目录 再进行解析采集
                        FileInfo copiedFile = CommonHelper.CopyFileToExpirePath(sourceFile, expirePath);
                        DataTable infoTable = BaseUtils.CsvToDataTable(copiedFile.FullName);
                        StringBuilder stringBuilder = new StringBuilder();
                        DataTable configDt = dataRow.Table.Clone();
                        // 将 DataRow 添加到新的 DataTable 中
                        configDt.ImportRow(dataRow);
                        List<string> testItem = new List<string>() { "发送鼓风机及继电器开启LIN报文", "读取软件版本", "发送风量调节LIN报文", "测量鼓风机端电压", "发送LIN报文状态调整", "读取模式电机反馈状态报文", "读取ONOFF反馈状态报文", "检测模式电机反馈电压", "检测温度电机反馈电压", "发送LIN报文状态调整", "鼓风机端电压", "读取模式电机反馈状态报文", "读取ONOFF电机反馈状态报文", "模式电机反馈电压" };
                        for (int i = rowIndex; i < infoTable.Rows.Count; i++)
                        {
                            string[] rowLine = infoTable.Rows[i][0].ToString().Split('	');
                            string testResult = rowLine[0];
                            string sn = rowLine[1].Replace("'", "");
                            if (sn.Contains("Re") || sn.Length < 20)
                            {
                                continue;
                            }
                            string linkSn = sn.Substring(0, 14);
                            string mainSn = sn.Substring(14);
                            string userID = rowLine[2];
                            string testDateTime = rowLine[3];

                            if (testResult == "FAIL")
                            {
                                for (int j = 0; j < testItem.Count; j++)
                                {
                                    string testVal = string.Empty;
                                    if (rowLine.Length > j + 7)
                                    {
                                        testVal = rowLine[j + 7];
                                    }
                                    stringBuilder.Append($"insert into sfcdatdevice_fctelectricaltestrecords(ProductSN,TestItem,TestVal,Result,UserID)" +
                                            $"values('{mainSn}','{testItem[j]}','{testVal}','{testResult}','{userID}');");
                                }

                            }

                            //是否过站
                            string isProcess = "0";
                            //过站信息
                            string failReason = string.Empty;
                            if (testResult == "PASS")
                            {
                                //过站方法
                                var result = SendProcess(configDt, mainSn, wocode, sfcno, productID, linkSn);

                                BaseUtils._eventMsg.ErrorMsg = $"过站返回值 result {result}";
                                if (result != null)
                                {
                                    ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                    // 获取status值

                                    //0执行失败 1执行成功
                                    if (jsonObject.Status == "1")
                                    {
                                        BaseUtils._eventMsg.Info = $"SN【{linkSn}】【过站成功】{result}";
                                        isProcess = "1";
                                    }
                                    else
                                    {
                                        isProcess = "2";
                                        failReason = jsonObject._ReturnMsg;
                                    }
                                }
                            }
                            stringBuilder.Append("insert into sfcdatdevice_fctelectricalmain(wocode,sfcno,barcode,TestResult,TestDateTime,MachCode,MachName,IsProcess,FailReason,AreaID,ProductID,ProductName,Creator,FileUpdateTime,RowIndex) " +
                                                 $"values('{wocode}','{sfcno}','{mainSn}','{testResult}','{testDateTime}','{deviceId}','{deviceName}','{isProcess}','{failReason}','{areaID}','{productID}','{productName}','{userID}','{copiedFile.LastWriteTime}','{i + 1}');");


                        }
                        if (stringBuilder.Length > 0)
                        {
                            CommonHelper.ExeSql(stringBuilder);
                        }


                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                        Thread.Sleep(2000);
                    }
                    Thread.Sleep(2000);
                }
            }
        }

        #endregion

        #region 锦飞串口通信
        public static void JF_UART_GatherSmtMachine(DataRow dataRow, string sfcno)
        {

            // 定义串口对象
            SerialPort serialPort = new SerialPort();
            // 设置串口参数（默认值）
            serialPort.PortName = ConfigurationManager.AppSettings["PortName"];  // 端口号
            serialPort.BaudRate = int.Parse(ConfigurationManager.AppSettings["BaudRate"]);    // 波特率
            serialPort.DataBits = int.Parse(ConfigurationManager.AppSettings["DataBits"]);       // 数据位
            serialPort.Parity = Parity.None; // 校验位
            serialPort.StopBits = StopBits.One; // 停止位
            serialPort.Handshake = Handshake.None; // 流控


            string valueStr = string.Empty;
            string linkSn = string.Empty;
            while (portState)
            {
                try
                {
                    lock (lockObj)
                    {

                        try
                        {
                            if (!serialPort.IsOpen)
                            {
                                try
                                {
                                    // 尝试打开串口
                                    serialPort.Open();
                                    BaseUtils._eventMsg.Info = $"【串口开启】";
                                }
                                catch (System.IO.IOException ex) when (ex.Message.Contains("被占用"))
                                {
                                    // 若串口被占用，输出错误信息并跳过本次循环
                                    BaseUtils._eventMsg.ErrorMsg = $"【串口被占用】{ex.Message}";
                                    continue;
                                }
                            }


                            serialPort.DataReceived += (sender, e) =>
                            {
                                SerialPort sp = (SerialPort)sender;

                                string barcodeData = sp.ReadExisting();
                                valueStr += barcodeData;
                                if (valueStr.Length > 66)
                                {
                                    BaseUtils._eventMsg.Info = $"【监听数据】{valueStr}";

                                    // 解析条码信息
                                    int startIndex = valueStr.IndexOf("12#");
                                    if (startIndex != -1)
                                    {
                                        startIndex += 3; // 跳过 "12#"
                                        int endIndex = valueStr.IndexOf('$', startIndex);
                                        if (endIndex != -1)
                                        {
                                            linkSn = valueStr.Substring(startIndex, endIndex - startIndex);
                                        }
                                    }
                                    BaseUtils._eventMsg.Info = $"【linkSn】{linkSn}";
                                    valueStr = string.Empty;
                                }

                            };
                        }
                        catch (Exception ex)
                        {
                            BaseUtils._eventMsg.ErrorMsg = $"【串口通信出错】{ex.Message}";
                            continue; // 出现串口错误，跳过本次循环
                        }

                        if (!string.IsNullOrEmpty(linkSn))
                        {

                            // 初始化参数
                            var devicePath = dataRow["CollectPath"].ToString();
                            string expirePath = dataRow["TransferPath"].ToString();
                            var userName = dataRow["userName"].ToString();
                            var passWord = dataRow["passWord"].ToString();
                            var deviceId = dataRow["DeviceId"].ToString();
                            var deviceName = dataRow["DeviceName"].ToString();

                            BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";

                            DataTable wocodekdt = CommonHelper.GetDataTable($"select * from sfcdatwocode where sfcno='{sfcno}';");
                            if (wocodekdt.Rows.Count <= 0)
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"无制令单数据{sfcno}";
                                continue;
                            }
                            string productID = wocodekdt.Rows[0]["productID"].ToString();
                            string productName = wocodekdt.Rows[0]["ProductName"].ToString();
                            string wocode = wocodekdt.Rows[0]["wocode"].ToString();
                            string areaID = wocodekdt.Rows[0]["AreaID"].ToString();

                            DataTable configDt = dataRow.Table.Clone();
                            // 将 DataRow 添加到新的 DataTable 中
                            configDt.ImportRow(dataRow);

                            DataTable mainSnDt = CommonHelper.GetDataTable($"SELECT * from sfcdatlinksn WHERE linksn='{linkSn}' or mainsn='{linkSn}';");
                            if (mainSnDt.Rows.Count == 0) // 修正逻辑，应该是没找到时提示
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"SN【{linkSn}】【未找到主SN】";
                                linkSn = string.Empty;
                                continue; // 没找到主SN，跳过本次循环
                            }
                            string mainSn = mainSnDt.Rows[0]["mainsn"].ToString();
                            BaseUtils._eventMsg.Info = $"mainSn【{mainSn}】";
                            // 过站方法
                            var result = SendProcess(configDt, mainSn, wocode, sfcno, productID, linkSn);

                            BaseUtils._eventMsg.Info = $"过站返回值 result {result}";
                            if (result != null)
                            {
                                ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                // 获取status值
                                // 0执行失败 1执行成功
                                if (jsonObject.Status == "1")
                                {
                                    BaseUtils._eventMsg.Info = $"SN【{linkSn}】【过站成功】{result}";
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                }
                Thread.Sleep(2000);
            }



        }
        #endregion
        public static void JF_AOI_2dGatherSmtMachine(string DeviceId)
        {
            //string DeviceId = ConfigurationManager.AppSettings["DeviceId"];
            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
            // 初始化参数
            var devicePath = configDt.Rows[0]["CollectPath"].ToString();
            var expirePath = configDt.Rows[0]["TransferPath"].ToString();
            var userName = configDt.Rows[0]["userName"].ToString();
            var passWord = configDt.Rows[0]["passWord"].ToString();
            var deviceId = configDt.Rows[0]["DeviceId"].ToString();
            var deviceName = configDt.Rows[0]["DeviceName"].ToString();
            var dateDay = DateTime.Now.ToString("yyyyMMdd");
            var areaId = configDt.Rows[0]["AreaId"].ToString();
            BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";
            lock (lockObj)
            {
                //while (aoi2dState)
                {

                    try
                    {
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }

                        // 获取并处理CSV文件
                        var fileList = BaseUtils.GetExcelDicList(devicePath, "*.txt");
                        if (!fileList.Any()) return;
                        BaseUtils._eventMsg.Info = $"本次检查到{fileList.Length}数据";
                        var movePath = Path.Combine(expirePath, dateDay);
                        foreach (var file in fileList)
                        {
                            try
                            {
                                Thread.Sleep(5000);
                                StringBuilder stringBuilder = new StringBuilder();
                                int index = 0;
                                using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite))
                                using (StreamReader sr = new StreamReader(fs, Encoding.ASCII))
                                {
                                    string line;
                                    string guid = Guid.NewGuid().ToString();
                                    string wocode = string.Empty;
                                    string sfcno = string.Empty;
                                    string productID = string.Empty;
                                    string allresult = string.Empty;
                                    string pcbcode = string.Empty;
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        string[] linStr = line.Split(',');

                                        if (index == 0)
                                        {
                                            allresult = linStr[2];
                                            pcbcode = linStr[3];
                                            DataTable wocodeDt = CommonHelper.GetDataTable($@"
                                                                                   SELECT 
                                                                                       sfcdatwocode.WOCode,
                                                                                       sfcdatwocode.SfcNo,
                                                                                       sfcdatwocode.ProductID,
                                                                                       sfcdatwocode.ProductName,
                                                                                       sfcdatmes_vstorage_producing.SN
                                                                                   FROM 
                                                                                       sfcdatwocode
                                                                                   JOIN 
                                                                                       sfcdatmes_vstorage_producing ON sfcdatwocode.SfcNo = sfcdatmes_vstorage_producing.SFCNo
                                                                                   WHERE 
                                                                                       sfcdatmes_vstorage_producing.SN ='{pcbcode}';
                                                                                   ");
                                            if (wocodeDt.Rows.Count > 0)
                                            {
                                                wocode = wocodeDt.Rows[0]["Wocode"].ToString();
                                                sfcno = wocodeDt.Rows[0]["SfcNo"].ToString();
                                                productID = wocodeDt.Rows[0]["productID"].ToString();
                                            }


                                            stringBuilder.Append("insert into sfcdatdevice_jfaoi(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,isProcess,failReason,Guid) values");
                                            string isProcess = "0";
                                            string failReason = string.Empty;
                                            BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【开始过站】";
                                            if (allresult == "PASS")
                                            {
                                                //过站方法
                                                var result = SendProcess(configDt, pcbcode, wocode, sfcno, productID, null);

                                                if (result != null)
                                                {
                                                    ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                                    // 获取status值

                                                    //0执行失败 1执行成功
                                                    if (jsonObject.Status == "1")
                                                    {
                                                        BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【过站成功】{result}";
                                                        new LogHelper().Info($"SN【{pcbcode}】【过站成功】{result}");
                                                        isProcess = "1";
                                                    }
                                                    else
                                                    {
                                                        BaseUtils._eventMsg.ErrorMsg = $"SN【{pcbcode}】【过站失败】{result}";
                                                        new LogHelper().Error($"SN【{pcbcode}】【过站失败】{result}");
                                                        isProcess = "2";
                                                        failReason = jsonObject._ReturnMsg;
                                                    }
                                                }

                                            }
                                            stringBuilder.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{allresult}','{deviceId}','{deviceName}','{pcbcode}','{isProcess}','{failReason}','{guid}'),");

                                            if (stringBuilder.Length > 0)
                                            {
                                                stringBuilder.Length--;  // 删除最后一个字符
                                                stringBuilder.Append(";");  // 添加分号
                                            }
                                        }

                                        if (index != 0 && allresult != "PASS")
                                        {
                                            string position = linStr[1].ToString();
                                            string result = linStr[7];
                                            string defect_code = linStr[4];
                                            string defect_description = linStr[5];
                                            stringBuilder.Append("insert into sfcdatdevice_jfaoi_details(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,Guid,position,defect_code,defect_description) values");
                                            stringBuilder.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{result}','{deviceId}','{deviceName}','{pcbcode}','{guid}','{position}','{defect_code}','{defect_description}');");
                                        }
                                        index++;
                                    }
                                }
                                if (stringBuilder.Length > 0)
                                {
                                    CommonHelper.ExeSql(stringBuilder);
                                }
                            }
                            catch (Exception ex)
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex}";
                            }
                            finally
                            {

                                FileMove(movePath, file);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                        Thread.Sleep(2000);
                    }
                    Thread.Sleep(2000);

                }
            }
        }
        public static void JF_AOI_3dGatherSmtMachine(string DeviceId)
        {

            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
            // 初始化参数
            var devicePath = configDt.Rows[0]["CollectPath"].ToString();
            var expirePath = configDt.Rows[0]["TransferPath"].ToString();
            var userName = configDt.Rows[0]["userName"].ToString();
            var passWord = configDt.Rows[0]["passWord"].ToString();
            var deviceId = configDt.Rows[0]["DeviceId"].ToString();
            var deviceName = configDt.Rows[0]["DeviceName"].ToString();
            var dateDay = DateTime.Now.ToString("yyyyMMdd");
            var areaId = configDt.Rows[0]["AreaId"].ToString();
            BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";
            lock (lockObj)
            {
                //while (aoi3dState)
                {
                    try
                    {
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }
                        var fileList = BaseUtils.GetExcelDicList(devicePath, "*.txt");
                        if (!fileList.Any()) return;
                        BaseUtils._eventMsg.Info = $"本次检查到{fileList.Length}数据";

                        var movePath = Path.Combine(expirePath, dateDay);
                        foreach (var file in fileList)
                        {
                            Thread.Sleep(3000);
                            try
                            {


                                StringBuilder stringBuilder = new StringBuilder();
                                int index = 0;
                                using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite))
                                using (StreamReader sr = new StreamReader(fs, Encoding.ASCII))
                                {
                                    string line;
                                    string guid = Guid.NewGuid().ToString();
                                    string wocode = string.Empty;
                                    string sfcno = string.Empty;
                                    string productID = string.Empty;
                                    string allresult = string.Empty;
                                    string pcbcode = string.Empty;
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        string[] linStr = line.Split(',');



                                        if (index == 0)
                                        {
                                            allresult = linStr[2];
                                            pcbcode = linStr[3];
                                            DataTable pcbdt = CommonHelper.GetDataTable($"SELECT pcbcode from zzdtrs_bigpcbtopcb WHERE bigpcb in (SELECT bigpcb from zzdtrs_bigpcbtopcb WHERE pcbcode='{pcbcode}');");
                                            List<string> pcbCodeList = (from row in pcbdt.AsEnumerable()
                                                                        select row.Field<string>("pcbcode")).ToList();

                                            if (pcbCodeList.Count == 0)
                                            {
                                                BaseUtils._eventMsg.ErrorMsg = $"无小板数据 {pcbcode}";
                                                Thread.Sleep(2000);
                                                continue;
                                            }
                                            DataTable wocodeDt = CommonHelper.GetDataTable($@"
                                                                                   SELECT 
                                                                                       sfcdatwocode.WOCode,
                                                                                       sfcdatwocode.SfcNo,
                                                                                       sfcdatwocode.ProductID,
                                                                                       sfcdatwocode.ProductName,
                                                                                       sfcdatmes_vstorage_producing.SN
                                                                                   FROM 
                                                                                       sfcdatwocode
                                                                                   JOIN 
                                                                                       sfcdatmes_vstorage_producing ON sfcdatwocode.SfcNo = sfcdatmes_vstorage_producing.SFCNo
                                                                                   WHERE 
                                                                                       sfcdatmes_vstorage_producing.SN IN ('{string.Join("','", pcbCodeList)}');
                                                                                   ");
                                            if (wocodeDt.Rows.Count > 0)
                                            {
                                                wocode = wocodeDt.Rows[0]["Wocode"].ToString();
                                                sfcno = wocodeDt.Rows[0]["SfcNo"].ToString();
                                                productID = wocodeDt.Rows[0]["productID"].ToString();
                                            }


                                            stringBuilder.Append("insert into sfcdatdevice_jfaoi(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,isProcess,failReason,Guid) values");

                                            foreach (var sn in pcbCodeList)
                                            {

                                                string isProcess = "0";
                                                string failReason = string.Empty;
                                                BaseUtils._eventMsg.Info = $"SN【{sn}】【开始过站】";
                                                if (allresult == "PASS")
                                                {
                                                    //过站方法
                                                    var result = SendProcess(configDt, sn, wocode, sfcno, productID, null);
                                                    if (result != null)
                                                    {
                                                        ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                                        // 获取status值

                                                        //0执行失败 1执行成功
                                                        if (jsonObject.Status == "1")
                                                        {
                                                            BaseUtils._eventMsg.Info = $"SN【{sn}】【过站成功】{result}";
                                                            new LogHelper().Info($"SN【{sn}】【过站成功】{result}");
                                                            isProcess = "1";
                                                        }
                                                        else
                                                        {
                                                            BaseUtils._eventMsg.ErrorMsg = $"SN【{sn}】【过站失败】{result}";
                                                            new LogHelper().Error($"SN【{sn}】【过站失败】{result}");
                                                            isProcess = "2";
                                                            failReason = jsonObject._ReturnMsg;
                                                        }
                                                    }

                                                }

                                                stringBuilder.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{allresult}','{deviceId}','{deviceName}','{sn}','{isProcess}','{failReason}','{guid}'),");

                                            }
                                            if (stringBuilder.Length > 0)
                                            {
                                                stringBuilder.Length--;  // 删除最后一个字符
                                                stringBuilder.Append(";");  // 添加分号
                                            }
                                        }

                                        if (index != 0 && allresult != "PASS")
                                        {
                                            string position = linStr[1].ToString();
                                            string result = linStr[7];
                                            string defect_code = linStr[4];
                                            string defect_description = linStr[5];
                                            stringBuilder.Append("insert into sfcdatdevice_jfaoi_details(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,Guid,position,defect_code,defect_description) values");
                                            stringBuilder.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{result}','{deviceId}','{deviceName}','{pcbcode}','{guid}','{position}','{defect_code}','{defect_description}');");
                                        }
                                        index++;
                                    }
                                }
                                if (stringBuilder.Length > 0)
                                {
                                    CommonHelper.ExeSql(stringBuilder);
                                }
                            }
                            catch (Exception ex)
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex}";
                            }
                            finally
                            {

                                FileMove(movePath, file);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                        Thread.Sleep(2000);
                    }
                    Thread.Sleep(2000);

                }
            }
        }
        public static void JF_AOI_DIPGatherSmtMachine(string DeviceId)
        {

            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
            // 初始化参数
            var devicePath = configDt.Rows[0]["CollectPath"].ToString();
            var expirePath = configDt.Rows[0]["TransferPath"].ToString();
            var userName = configDt.Rows[0]["userName"].ToString();
            var passWord = configDt.Rows[0]["passWord"].ToString();
            var deviceId = configDt.Rows[0]["DeviceId"].ToString();
            var deviceName = configDt.Rows[0]["DeviceName"].ToString();
            var dateDay = DateTime.Now.ToString("yyyyMMdd");
            var areaId = configDt.Rows[0]["AreaId"].ToString();
            BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";
            lock (lockObj)
            {
                //while (aoi3dState)
                {
                    try
                    {
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }
                        var fileList = BaseUtils.GetExcelDicList(devicePath, "*.txt");
                        if (!fileList.Any()) return;
                        BaseUtils._eventMsg.Info = $"本次检查到{fileList.Length}数据";

                        var movePath = Path.Combine(expirePath, dateDay);
                        foreach (var file in fileList)
                        {
                            Thread.Sleep(2000);
                            try
                            {
                                int index = 0;
                                using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite))
                                using (StreamReader sr = new StreamReader(fs, Encoding.ASCII))
                                {
                                    StringBuilder str_aoimain = new StringBuilder();
                                    StringBuilder str_aoidetaile = new StringBuilder();
                                    string line;
                                    string guid = Guid.NewGuid().ToString();
                                    string wocode = string.Empty;
                                    string sfcno = string.Empty;
                                    string productID = string.Empty;
                                    string allresult = string.Empty;
                                    string pcbcode = string.Empty;
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        if (index <= 17)
                                        {
                                            string[] linStr = line.Split(':');
                                            switch (index)
                                            {
                                                case 1:
                                                    pcbcode = linStr[1];
                                                    break;
                                                case 12:
                                                    allresult = linStr[1] == "P" ? "PASS" : "FAIL";
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }
                                        else
                                        {
                                            string[] linStr = line.Split(',');
                                            string position = linStr[0].ToString();
                                            string result = allresult;
                                            string defect_code = linStr[3];
                                            string defect_description = linStr[3];
                                            str_aoidetaile.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{allresult}','{deviceId}','{deviceName}','{pcbcode}','{guid}','{position}','{defect_code}','{defect_description}'),");
                                        }
                                        index++;
                                    }
                                    if (!string.IsNullOrEmpty(allresult))
                                    {

                                        DataTable wocodeDt = CommonHelper.GetDataTable($@"
                                        SELECT 
                                        sfcdatwocode.WOCode,
                                        sfcdatwocode.SfcNo,
                                        sfcdatwocode.ProductID,
                                        sfcdatwocode.ProductName,
                                        sfcdatmes_vstorage_producing.SN
                                        FROM 
                                        sfcdatwocode
                                        JOIN 
                                        sfcdatmes_vstorage_producing ON sfcdatwocode.SfcNo = sfcdatmes_vstorage_producing.SFCNo
                                        WHERE 
                                        sfcdatmes_vstorage_producing.SN = ('{pcbcode}');");
                                        if (wocodeDt.Rows.Count > 0)
                                        {
                                            wocode = wocodeDt.Rows[0]["Wocode"].ToString();
                                            sfcno = wocodeDt.Rows[0]["SfcNo"].ToString();
                                            productID = wocodeDt.Rows[0]["productID"].ToString();
                                        }
                                        string isProcess = "0";
                                        string failReason = string.Empty;
                                        BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【开始过站】";

                                        if (allresult == "PASS")
                                        {
                                            //过站方法
                                            var result = SendProcess(configDt, pcbcode, wocode, sfcno, productID, null);
                                            if (result != null)
                                            {
                                                ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                                // 获取status值
                                                //0执行失败 1执行成功
                                                if (jsonObject.Status == "1")
                                                {
                                                    BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【过站成功】{result}";
                                                    new LogHelper().Info($"SN【{pcbcode}】【过站成功】{result}");
                                                    isProcess = "1";
                                                }
                                                else
                                                {
                                                    BaseUtils._eventMsg.ErrorMsg = $"SN【{pcbcode}】【过站失败】{result}";
                                                    new LogHelper().Error($"SN【{pcbcode}】【过站失败】{result}");
                                                    isProcess = "2";
                                                    failReason = jsonObject._ReturnMsg;
                                                }
                                            }
                                            str_aoimain.Append("insert into sfcdatdevice_jfaoi(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,isProcess,failReason,Guid) values ");
                                            str_aoimain.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{allresult}','{deviceId}','{deviceName}','{pcbcode}','{isProcess}','{failReason}','{guid}');");
                                            CommonHelper.ExeSql(str_aoimain);
                                        }
                                        else if (str_aoidetaile.Length > 0)
                                        {
                                            str_aoimain.Append("insert into sfcdatdevice_jfaoi(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,isProcess,failReason,Guid) values");
                                            str_aoimain.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{allresult}','{deviceId}','{deviceName}','{pcbcode}','{isProcess}','{failReason}','{guid}');");

                                            str_aoimain.Append("insert into sfcdatdevice_jfaoi_details(Wocode,SFCNO,AreaId,Product,Result,DeviceId,DeviceName,BarCode,Guid,position,defect_code,defect_description) values ");
                                            str_aoimain.Append(str_aoidetaile.Remove(str_aoidetaile.Length - 1, 1).Append(";").ToString());
                                            CommonHelper.ExeSql(str_aoimain);
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                            finally
                            {
                                FileMove(movePath, file);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                    }

                }
            }
        }
        /// <summary>
        /// 祥巨
        /// </summary>
        /// <param name="DeviceId"></param>
        public static void XJ_FCTGatherSmtMachine(string DeviceId)
        {

            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
            // 初始化参数
            var devicePath = configDt.Rows[0]["CollectPath"].ToString();
            var expirePath = configDt.Rows[0]["TransferPath"].ToString();
            var userName = configDt.Rows[0]["userName"].ToString();
            var passWord = configDt.Rows[0]["passWord"].ToString();
            var deviceId = configDt.Rows[0]["DeviceId"].ToString();
            var deviceName = configDt.Rows[0]["DeviceName"].ToString();
            var dateDay = DateTime.Now.ToString("yyyyMMdd");
            var areaId = configDt.Rows[0]["AreaId"].ToString();
            BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";
            lock (lockObj)
            {
                //while (aoi3dState)
                {
                    try
                    {
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }
                        var fileList = BaseUtils.GethtmlList(devicePath, "*.html");
                        if (!fileList.Any()) return;
                        BaseUtils._eventMsg.Info = $"本次检查到{fileList.Length}数据";

                        var movePath = expirePath; //Path.Combine(expirePath, dateDay);
                        List<string> allresultList = new List<string>();
                        foreach (var file in fileList)
                        {
                            // string movePathpin = ;
                            movePath = Path.Combine(expirePath, BaseUtils.GetThreeLevelsUpDirectory(file));
                            StringBuilder stringBuilder = new StringBuilder();
                            string guid = Guid.NewGuid().ToString();
                            string wocode = string.Empty;
                            string sfcno = string.Empty;
                            string productID = string.Empty;
                            string allresult = "Fail";
                            string productName = string.Empty;
                            string pcbcode = Regex.Match(file.Name, @"^[^\[]+").Value;

                            DataTable wocodeDt = CommonHelper.GetDataTable($@"
                                                                                   SELECT 
                                                                                       sfcdatwocode.WOCode,
                                                                                       sfcdatwocode.SfcNo,
                                                                                       sfcdatwocode.ProductID,
                                                                                       sfcdatwocode.ProductName,
                                                                                       sfcdatmes_vstorage_producing.SN
                                                                                   FROM 
                                                                                       sfcdatwocode
                                                                                   JOIN 
                                                                                       sfcdatmes_vstorage_producing ON sfcdatwocode.SfcNo = sfcdatmes_vstorage_producing.SFCNo
                                                                                   WHERE 
                                                                                       sfcdatmes_vstorage_producing.SN = ('{pcbcode}');
                                                                                   ");
                            if (wocodeDt.Rows.Count > 0)
                            {
                                wocode = wocodeDt.Rows[0]["Wocode"].ToString();
                                sfcno = wocodeDt.Rows[0]["SfcNo"].ToString();
                                productID = wocodeDt.Rows[0]["productID"].ToString();
                                productName = wocodeDt.Rows[0]["productName"].ToString();
                            }
                            // 加载HTML文档
                            var doc = new HtmlDocument();
                            doc.Load(file.FullName);

                            // 获取所有的TR节点
                            var trNodes = doc.DocumentNode.SelectNodes("//tr");

                            if (trNodes != null)
                            {
                                foreach (var trNode in trNodes)
                                {
                                    // 获取当前TR下的所有TD节点
                                    var tdNodes = trNode.SelectNodes(".//td");

                                    if (tdNodes != null)
                                    {
                                        // 提取每个TD的内容
                                        string[] tdContents = tdNodes.Select(td => td.InnerText.Trim()).ToArray();
                                        string status = tdContents[1];
                                        if (string.IsNullOrEmpty(status) || status == "Done")
                                        {
                                            continue;
                                        }
                                        allresultList.Add(status);

                                        if (status != "Passed")
                                        {
                                            string testItem = tdContents[0];
                                            string low_L = tdContents[4];
                                            string high_L = tdContents[5];
                                            string testVal = tdContents[2];
                                            stringBuilder.Append($"insert into sfcdatdevice_fctelectricaltestrecords(ProductSN,TestItem,Low_L,High_L,TestVal,Result,UserID) values" +
                                                $"('{pcbcode}','{testItem}','{low_L}','{high_L}','{testVal}','{status}','{deviceId}');");

                                        }
                                    }
                                }
                                //无Failed情况则过站
                                string isProcess = "0";
                                string failReason = string.Empty;
                                if (!allresultList.Contains("Failed"))
                                {
                                    allresult = "PASS";
                                    //过站方法
                                    var result = SendProcess(configDt, pcbcode, wocode, sfcno, productID, null);
                                    if (result != null)
                                    {
                                        ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                        // 获取status值

                                        //0执行失败 1执行成功
                                        if (jsonObject.Status == "1")
                                        {
                                            BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【过站成功】{result}";
                                            new LogHelper().Info($"SN【{pcbcode}】【过站成功】{result}");
                                            isProcess = "1";
                                        }
                                        else
                                        {
                                            BaseUtils._eventMsg.ErrorMsg = $"SN【{pcbcode}】【过站失败】{result}";
                                            new LogHelper().Error($"SN【{pcbcode}】【过站失败】{result}");
                                            isProcess = "2";
                                            failReason = jsonObject._ReturnMsg;
                                        }
                                    }
                                }
                                stringBuilder.Append("insert into sfcdatdevice_fctelectricalmain(Wocode,SFCNO,AreaId,ProductID,ProductName,TestResult,TestDateTime,MachCode,DeviceName,BarCode,isProcess,failReason,Guid,Creator) values");
                                stringBuilder.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{productName}','{allresult}','{file.LastWriteTime}','{deviceId}','{deviceName}','{pcbcode}','{isProcess}','{failReason}','{guid}','{deviceId}');");


                            }
                            else
                            {
                                continue;
                            }
                            if (stringBuilder.Length > 0)
                            {
                                CommonHelper.ExeSql(stringBuilder);
                                FileMove(movePath, file);
                            }

                        }


                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                        Thread.Sleep(2000);
                    }
                    Thread.Sleep(2000);

                }
            }
        }
        /// <summary>
        /// 派捷ICT
        /// </summary>
        /// <param name="DeviceId"></param>
        public static void PJ_ICTGatherSmtMachine(string DeviceId, string sfcno)
        {

            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
            DataTable dt_wocode = CommonHelper.GetDataTable($"SELECT *  from sfcdatwocode WHERE SfcNo='{sfcno}' ;");

            // 初始化参数
            var devicePath = configDt.Rows[0]["CollectPath"].ToString();
            var expirePath = configDt.Rows[0]["TransferPath"].ToString();
            var userName = configDt.Rows[0]["userName"].ToString();
            var passWord = configDt.Rows[0]["passWord"].ToString();
            var deviceId = configDt.Rows[0]["DeviceId"].ToString();
            var deviceName = configDt.Rows[0]["DeviceName"].ToString();
            var dateDay = DateTime.Now.ToString("yyyyMMdd");
            var areaId = configDt.Rows[0]["AreaId"].ToString();
            //初始化工单、产品等信息
            string wocode = dt_wocode.Rows[0]["WOCode"].ToString();
            string productID = dt_wocode.Rows[0]["ProductID"].ToString();
            string productName = dt_wocode.Rows[0]["ProductName"].ToString();
            BaseUtils._eventMsg.Info = $"【开始采集】DeviceName{deviceName} DeviceId{deviceId}";
            lock (lockObj)
            {
                //while (aoi3dState)
                {
                    try
                    {
                        // 连接网络共享
                        if (!string.IsNullOrEmpty(userName))
                        {
                            BaseUtils.DisconnectNetworkDrive(devicePath);
                            BaseUtils.ConnectState(devicePath, userName, passWord);
                        }
                        var dateMonth = DateTime.Now.ToString("yyyy_MM");
                        devicePath = Path.Combine(devicePath, productName, dateMonth);
                        FileInfo[] fileList = BaseUtils.GetExcelDicList(devicePath, "*.csv");
                        if (!fileList.Any()) return;
                        fileList = fileList
                                  .Where(f => !f.Name.StartsWith("----"))
                                  .ToArray();

                        BaseUtils._eventMsg.Info = $"本次检查到{fileList.Length}数据";

                        var movePath = Path.Combine(expirePath, dateDay);
                        List<string> allresultList = new List<string>();
                        foreach (var file in fileList)
                        {
                            // string movePathpin = ;
                            movePath = Path.Combine(expirePath, BaseUtils.GetThreeLevelsUpDirectory(file));

                            StringBuilder stringBuilder = new StringBuilder();
                            string guid = Guid.NewGuid().ToString();


                            DataTable screenDt = CommonHelper.CsvToDataTable(file.FullName);

                            string testDateTime = screenDt.Rows[0][1].ToString();
                            string programId = screenDt.Rows[1][1].ToString();
                            string pcbcode = screenDt.Rows[8][1].ToString();
                            string allresult = screenDt.Rows[12][1].ToString();
                            string testTime = screenDt.Rows[15][1].ToString();

                            //DataTable wocodeDt = CommonHelper.GetDataTable($@"
                            //                                                       SELECT 
                            //                                                           sfcdatwocode.WOCode,
                            //                                                           sfcdatwocode.SfcNo,
                            //                                                           sfcdatwocode.ProductID,
                            //                                                           sfcdatwocode.ProductName,
                            //                                                           sfcdatmes_vstorage_producing.SN
                            //                                                       FROM 
                            //                                                           sfcdatwocode
                            //                                                       JOIN 
                            //                                                           sfcdatmes_vstorage_producing ON sfcdatwocode.SfcNo = sfcdatmes_vstorage_producing.SFCNo
                            //                                                       WHERE 
                            //                                                           sfcdatmes_vstorage_producing.SN = ('{pcbcode}');
                            //                                                       ");
                            //if (wocodeDt.Rows.Count > 0)
                            //{
                            //    wocode = wocodeDt.Rows[0]["Wocode"].ToString();
                            //    sfcno = wocodeDt.Rows[0]["SfcNo"].ToString();
                            //    productID = wocodeDt.Rows[0]["productID"].ToString();
                            //    productName = wocodeDt.Rows[0]["productName"].ToString();
                            //}

                            for (int i = 18; i < screenDt.Rows.Count; i++)
                            {

                                string status = screenDt.Rows[i][21].ToString();
                                if (string.IsNullOrEmpty(status) || status == "Skip" || status != "Fail")
                                {
                                    continue;
                                }
                                //测试项
                                string testName = screenDt.Rows[i][4].ToString();
                                string aCTval = screenDt.Rows[i][6].ToString();
                                int numbersOnly = int.Parse(Regex.Replace(aCTval, @"[^\d]", ""));

                                int maxProportion = int.Parse(screenDt.Rows[i][7].ToString().Replace("%", ""));
                                int minProportion = int.Parse(screenDt.Rows[i][8].ToString().Replace("%", ""));
                                string testVal = screenDt.Rows[i][19].ToString();
                                double maxval = numbersOnly + (numbersOnly * maxProportion / 100.0);
                                double minval = numbersOnly - (numbersOnly * (minProportion / 100.0));


                                stringBuilder.Append($"insert into sfcdatdevice_jfict_details(Wocode,SFCNO,AreaId,ProductID,DeviceId,DeviceName,Guid,BarCode,TestItem,SetMiniVal,SetMaxVal,TestVal,Result) values" +
                                    $"('{wocode}','{sfcno}','{areaId}','{productID}','{deviceId}','{deviceName}','{guid}','{pcbcode}','{testName}','{minval}','{maxval}','{testVal}','{status}');");


                            }
                            //无Failed情况则过站
                            string isProcess = "0";
                            string failReason = string.Empty;
                            BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【开始过站】";
                            if (allresult == "Pass")
                            {
                                //过站方法
                                var result = SendProcess(configDt, pcbcode, wocode, sfcno, productID, null);
                                if (result != null)
                                {
                                    ReturnMsg jsonObject = JsonConvert.DeserializeObject<ReturnMsg>(result);
                                    // 获取status值

                                    //0执行失败 1执行成功
                                    if (jsonObject.Status == "1")
                                    {
                                        BaseUtils._eventMsg.Info = $"SN【{pcbcode}】【过站成功】{result}";
                                        new LogHelper().Info($"SN【{pcbcode}】【过站成功】{result}");
                                        isProcess = "1";
                                    }
                                    else
                                    {
                                        BaseUtils._eventMsg.ErrorMsg = $"SN【{pcbcode}】【过站失败】{result}";
                                        new LogHelper().Error($"SN【{pcbcode}】【过站失败】{result}");
                                        isProcess = "2";
                                        failReason = jsonObject._ReturnMsg;
                                    }
                                }
                            }
                            stringBuilder.Append("insert into sfcdatdevice_jfict(Wocode,SFCNO,AreaId,ProductID,DeviceId, DeviceName,Guid,barcode, RecipeName,Result,TestItem, IsProcess,FailReason) values");
                            stringBuilder.Append($"('{wocode}','{sfcno}','{areaId}','{productID}','{deviceId}','{deviceName}','{guid}','{pcbcode}','{programId}','{allresult}','{testTime}','{isProcess}','{failReason}');");
                            if (stringBuilder.Length > 0)
                            {
                                CommonHelper.ExeSql(stringBuilder);
                                FileMove(movePath, file);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【采集出错】{ex.Message}";
                        Thread.Sleep(2000);
                        Thread.Sleep(2000);

                    }
                }
            }
        }
        #endregion


        #region 噪音测试 采集
        public static string ZY_GatherSmtMachine(string mainSN, string deviceId)
        {

            string messreturn = "执行成功";
            lock (lockObj)
            {
                try
                {
                    // 获取所有相关数据
                    DataSet dataSet = CommonHelper.GetDataSet($@"
                                       select DeviceType, DeviceName, DeviceModel, CollectPath, TransferPath,AreaID,DeviceName,deviceId  from deviceparameter where deviceId='{deviceId}';               
                                       SELECT mainsn from sfcdatlinksn WHERE linksn='{mainSN}' or mainsn='{mainSN}' ORDER BY createtime Desc LIMIT 1; ");


                    // 从 DataSet 中获取对应的 DataTable
                    DataTable configDt = dataSet.Tables[0]; // 设备配置表
                    DataTable mainLogDt = dataSet.Tables[1]; // link 关联表


                    if (configDt.Rows.Count <= 0 || string.IsNullOrEmpty(configDt.Rows[0]["CollectPath"].ToString()))
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】采集路径为空";

                        return $"【{deviceId}采集出错】采集路径为空";
                    }

                    if (mainLogDt.Rows.Count <= 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】该SN【{mainSN}】无主板码关联";
                        return $"【{deviceId}采集出错】该SN【{mainSN}】无主板码关联";
                    }


                    string oldMain = mainLogDt.Rows[0][0].ToString();
                    mainSN = oldMain;
                    DataTable wocodeDt = CommonHelper.GetDataTable($"SELECT WOCode,SfcNo,ProductID,ProductName,areaID from sfcdatwocode WHERE SfcNo in (SELECT SFCNo from sfcdatmes_vstorage_producing WHERE SN='{mainSN}');");
                    if (wocodeDt.Rows.Count <= 0)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】未找到SN关联数据{mainSN}";
                        return $"【{deviceId}采集出错】未找到SN关联数据{mainSN}";
                    }


                    //采集路径
                    string collectPath = configDt.Rows[0]["CollectPath"].ToString();
                    //转移后路径
                    string transferPath = configDt.Rows[0]["TransferPath"].ToString();

                    string DeviceName = configDt.Rows[0]["DeviceName"].ToString();
                    //工单
                    string wocode = wocodeDt.Rows[0]["wocode"].ToString();

                    string mateid = wocodeDt.Rows[0]["ProductID"].ToString();
                    //制令单
                    string sfcno = wocodeDt.Rows[0]["sfcno"].ToString();

                    string areaID = wocodeDt.Rows[0]["areaID"].ToString();

                    string productID = wocodeDt.Rows[0]["ProductID"].ToString();

                    string productName = wocodeDt.Rows[0]["productName"].ToString();
                    DateTime currentDate = DateTime.Now;

                    // 获取当前月和当前天
                    string currentMonth = currentDate.ToString("yyyyMM");  // 年月格式
                    string currentDay = currentDate.ToString("dd");        // 日格式

                    transferPath = Path.Combine(transferPath, currentMonth, currentDay);

                    if (!CommonHelper.IsServerConnected(collectPath))
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】 网络错误或延迟超过500毫秒";
                        return $"【{deviceId}采集出错】 网络错误或延迟超过500毫秒";
                    }
                    //获取最早的文件信息
                    FileInfo[] fileInfo = GetExcelDicList(collectPath, "*.csv");
                    if (fileInfo == null)
                    {

                        BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】 未有采集文件";
                        return $"【{deviceId}采集出错】 未有采集文件";
                    }
                    foreach (var file in fileInfo)
                    {


                        DataTable screenDt = CommonHelper.NewCsvToDataTable(file.FullName);
                        string guid = Guid.NewGuid().ToString();
                        StringBuilder stringBuildermain = new StringBuilder();


                        string testResult = screenDt.Rows[3][1].ToString();

                        if (testResult != "PASS")
                        {
                            for (int i = 2; i < screenDt.Columns.Count; i++)
                            {

                                if (string.IsNullOrEmpty(screenDt.Rows[0][i].ToString()))
                                {
                                    break;
                                }

                                string TestItem = screenDt.Rows[0][i].ToString();
                                string SetMiniVal = screenDt.Rows[1][i].ToString();
                                string SetMaxVal = screenDt.Rows[2][i].ToString();
                                string TestVal = screenDt.Rows[3][i].ToString();
                                stringBuildermain.Append("insert into sfcdatdevice_jfnoise_details(Wocode,SFCNO,AreaId,ProductID,Result,DeviceId,DeviceName,BarCode,Guid,TestItem,SetMiniVal,SetMaxVal,TestVal) values" +
                               $"('{wocode}','{sfcno}','{areaID}','{productID}','{testResult}','{deviceId}','{DeviceName}','{mainSN}','{guid}','{TestItem}','{SetMiniVal}','{SetMaxVal}','{TestVal}');");
                            }
                        }
                        //是否过站
                        string isProcess = "0";
                        //失败信息
                        string failReason = "";

                        #region 过站
                        if (testResult == "PASS")
                        {


                            //过站方法
                            var result = SendProcess(configDt, oldMain, wocode, sfcno, mateid);
                            BaseUtils._eventMsg.ErrorMsg = $"过站返回值 result {result}";
                            if (result != null)
                            {
                                JObject jsonObject = JObject.Parse(result);
                                // 获取status值
                                string status = jsonObject["Status"]?.Value<string>() ?? string.Empty;
                                if (string.IsNullOrEmpty(status))
                                {
                                    status = jsonObject["status"]?.Value<string>() ?? string.Empty;
                                }
                                //0执行失败 1执行成功
                                if (status == "1")
                                {
                                    BaseUtils._eventMsg.Info = $"SN【{mainSN}】【过站成功】{result}";
                                    isProcess = "1";
                                }
                                else
                                {
                                    isProcess = "2";
                                    failReason = jsonObject["_ReturnMsg"].Value<string>();
                                }
                            }
                        }
                        #endregion

                        stringBuildermain.Append($"insert into sfcdatdevice_jfnoise(Wocode,SFCNO,AreaId,ProductID,Result,DeviceId,DeviceName,BarCode,isProcess,failReason,Guid)values" +
                            $"('{wocode}','{sfcno}','{areaID}','{productID}','{testResult}','{deviceId}','{DeviceName}','{mainSN}','{isProcess}','{failReason}','{guid}')");

                        CommonHelper.ExeSql(stringBuildermain);

                        // 移动文件
                        FileMove(transferPath, file);

                    }
                }
                catch (Exception ex)
                {
                    BaseUtils._eventMsg.ErrorMsg = $"【{deviceId}采集出错】{ex.Message}";

                    return $"【{deviceId}采集出错】{ex.Message}";
                }

            }

            return messreturn;
        }
        #endregion
    }
}
